[英]Get records from one table excluding records from another
我正在嘗試從master table
中選擇與new table
記錄相匹配的記錄,但要排除new table
與old table
匹配的記錄。 urn
字段是它們之間的共同點。
我的查詢是這樣的:
SELECT *
FROM `master`
JOIN `new` ON `master`.`urn` = `new`.`urn`
LEFT JOIN `old` ON `old`.`urn` = `new`.`urn`
我確定這應該可以,但是不會返回正確數量的結果。
任何建議都非常歡迎!
對於這樣的查詢,我認為exists
和不exists
:
select m.*
from master m
where exists (select 1 from new n where n.urn = m.urn) and
not exists (select 1 from old o where o.urn = m.urn);
我寧願exists
顯式join
因為不存在new
重復項會導致結果集中重復項的危險。 我還發現它更緊密地代表了查詢的目的。
您可能缺少WHERE
條件,例如
SELECT *
FROM `master`
JOIN `new` ON `master`.`urn` = `new`.`urn`
LEFT JOIN `old` ON `old`.`urn` = `new`.`urn`
WHERE `old`.`urn` IS NULL;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.