Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select SQL for column 1 not in column 2

Tags:

sql

I have a table with four columns. The first column ID1 has one similar row in ID2. I like to select a query to get all rows from ID2, except the identical record. For instance:

ID1 Name1 ID2 Name2
-------------------
01  A     01  A
01  A     02  B
01  A     03  C
03  C     03  C
03  C     01  A
03  C     04  G

Select ID2, Name2 From table where ID2 <> ID1

Output should be:

ID2, Name2
----------
02   B
03   C
01   A
04   G

03/C and 01 A need to be here. If I use distinct, then it exludes all identical records of ID1, which I don't want to. I am using classic ASP to select ID1 groups in SELECt option list. if I select 01, then SELECT option list for ID2 appear. I only want to see all ID2 that is not in ID1.

enter image description here

Can someone help me please? Thanks.

like image 992
Jenny Tran Avatar asked Nov 20 '25 11:11

Jenny Tran


2 Answers

I think there is no need for explanation:

select id2, name2
from t
where (id1 <> id2) OR (name1 <> name2)
like image 171
forpas Avatar answered Nov 22 '25 02:11

forpas


I think you want not exists. But your result set doesn't seem to match the description of the question.

select id2, name2
from t
where not exists (select 1
                  from t t2
                  where t2.id1 = t.id2 and t2.name1 = t.name2
                 );
like image 26
Gordon Linoff Avatar answered Nov 22 '25 02:11

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!