簡體   English   中英

如何 select 來自 table1 的記錄,其中 table1.id 存在於 table2 的 id 列中?

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

我有兩張桌子

人們

name    id

man1    456
man2    123
man3    789

筆記

content id

testing 123
hello   456

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

我想寫兩個查詢。 一個從表people中選擇所有記錄,其中存在notes中的記錄,其中notes的 id 列中的值等於people.id

name    id

man1    456
man2    123

另一個從表people中選擇所有記錄,其中notes中的記錄不存在,其中notes的 id 列中的值等於people.id

content id

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM