1

我有两张桌子

人们

name    id

man1    456
man2    123
man3    789

笔记

content id

testing 123
hello   456

SELECT DISTINCT id FROM people是 的超集SELECT DISTINCT id FROM notes

我想写两个查询。一种从表中选择所有记录people,其中存在记录,notes其中 id 列中的notes值等于people.id

name    id

man1    456
man2    123

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

content id

man3    789
4

2 回答 2

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

于 2012-04-05T17:24:12.260 回答
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
于 2012-04-05T17:20:24.110 回答