简体   繁体   中英

sql compare two unique rows from the same table

Im hoping this is a straight forward question but I cannot work out the syntax for it.

I just need to find if a value within "ID" also exists in "ID2", lets say the tables called "teacher"

ID-ID2
10-1
11-2
12-13
13-4

the only match there is row 4 as 13 also exists in id2, so I would need to pull that out with a select query, can anybody advise? thanks.

Hi on top of this I have a second table called staff with the following setup

ID-Name
1-smith
2-jones
3-bruce

whereby ID is the same ID as in the teacher table, I think I need to join them here but im not sure what to do with the ID in the second table. The only information I need from the second table is the name so the Cartesian product should look like the above only with the processing done from table 1. thanks in advance

scrap that, solved it, thanks

Is this what you want?

select t.*
from teacher t
where exists (select 1 from teacher t2 where t2.id = t.id2);
select *
from teacher
where id in (select distinct id2 from teacher)

or

select t1.*
from teacher t1
join teacher t2 on t1.id = t2.id2
select t1.* 
from teacher as t1 ,teacher as t2 
where t1.ID = t2.ID2 and t1.ID > t2.ID2 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM