简体   繁体   中英

How to select the records from a table1 where table1.id exists in id column of table2?

I have two tables

people

name    id

man1    456
man2    123
man3    789

notes

content id

testing 123
hello   456

SELECT DISTINCT id FROM people is a superset of SELECT DISTINCT id FROM notes .

I would like to write two queries. One which selects all the records from the table people for which a record in notes exists where the value in the id column of notes is equal to people.id .

name    id

man1    456
man2    123

The other selects all the records from the table people for which a record in notes does not exist where the value in the id column of notes is equal to people.id

content id

man3    789
SELECT * FROM PEOPLE WHERE ID IN (SELECT ID FROM NOTES)

Results Man1 456 & Man2 123

SELECT * FROM PEOPLE WHERE ID NOT IN (SELECT ID FROM NOTES)

Results Man3 789

--people with notes
select distinct p.id, p.name
from people p
inner join notes n on p.id = n.id

--people with no notes
select p.id, p.name
from people p
left outer join notes n on p.id = n.id
where n.id is null

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