简体   繁体   English

SQL:如何使用 group by 从表中选择不在另一个表中的行?

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

Suppose that I have a table A with a column id (PK) and a table B with a foreign key to_id that refers to id.假设我有一个带有列 id (PK) 的表 A 和一个带有引用 id 的外键 to_id 的表 B。

I want to select all rows from A that aren't refered from B.我想从 A 中选择所有未从 B 引用的行。

I thought about the following approach:我想到了以下方法:

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

But I'd like to know if there is an approach that doens't use "NOT IN".但我想知道是否有一种不使用“NOT IN”的方法。

Something like:就像是:

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

This one doesn't work, but I'd like something like this if possible.这个不起作用,但如果可能的话,我想要这样的东西。

I want to select all rows from A that aren't refered from B.我想从 A 中选择所有未从 B 引用的行。

This reads like not exists :这读起来就像not exists

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

There is no need to group by whatsoever.没有必要以任何方式group by

Another typical approach is an anti- left join :另一种典型的方法是反left join

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

Just a left join and a where condition to pull only those which have a null as the b id.只是一个左连接和一个 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.

相关问题 如何显示一个表中没有的数据行? - How can I show rows from one table that aren't in another table? 如何使用SQL Select插入将行从一个表复制到另一个表 - How can i use SQL Select Insert to copy rows from one table to another 如何从一个SQL表中选择未出现在另一表中的项目 - How can I select items from one sql table that don't appear in another table 如何使用游标 for 循环在 PL SQL 中将行从一个表插入到另一个表? - How can I insert rows from one table to another in PL SQL using the cursor for loop? 如何对不熟悉的行进行分组? - How can I group rows that aren't familiar? 如何从一个表中选择所有行,并根据另一表计算字段值 - How can I select all rows from one table, calculating a field value based on another table T-SQL:我可以使用另一个表中的行来更新表吗? - T-SQL: Can I update a table using rows from another table? 如何从一个表中选择另一个表中不存在的行? - How can I select rows from a table that don't exist in another table? 我可以使用SQL将另一张表中的多行值组合为一行的多列吗? - Can I combine values from multiple rows in another table into multiple columns of one row using SQL? 选择表中不具有可为空外键的另一行中的行 - Select rows in a table which aren't in another one with a nullable foreign key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM