如何从table1中选择table1.id,其中table1.id存在于table2的id列中?

时间:2012-04-05 17:17:20

标签: mysql

我有两张桌子

name    id

man1    456
man2    123
man3    789

备注

content id

testing 123
hello   456

SELECT DISTINCT id FROM peopleSELECT DISTINCT id FROM notes的超集。

我想写两个查询。选择peoplenotes中记录的所有记录,notes的id列中的值等于people.id

name    id

man1    456
man2    123

另一个选择表people中的所有记录notes中的记录不存在,其中notes的id列中的值等于people.id }

content id

man3    789

2 个答案:

答案 0 :(得分:2)

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

结果Man1 456& Man2 123

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

结果Man3 789

答案 1 :(得分:1)

--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