簡體   English   中英

SQL:如何使用 group by 從表中選擇不在另一個表中的行?

[英]SQL: How can I select rows from a table that aren't in another one using group by?

假設我有一個帶有列 id (PK) 的表 A 和一個帶有引用 id 的外鍵 to_id 的表 B。

我想從 A 中選擇所有未從 B 引用的行。

我想到了以下方法:

select * from A group by id having id not in (select to_id from B);

但我想知道是否有一種不使用“NOT IN”的方法。

就像是:

select * from A, B group by id having id = to_id and count(to_id) = 0;

這個不起作用,但如果可能的話,我想要這樣的東西。

我想從 A 中選擇所有未從 B 引用的行。

這讀起來就像not exists

select a.*
from a
where not exists (select 1 from b where b.to_id = a.id)

沒有必要以任何方式group by

另一種典型的方法是反left join

select a.*
from a
left join b on b.to_id = a.id
where b.to_id is null

只是一個左連接和一個 where 條件,只提取那些以 null 作為 b id 的條件。

select a.*
from a
left join b on b.to_id = a.id
where b.to_id is null

暫無
暫無

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

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