Select ID 出现一次的所有记录SQL
Select all records where ID appears once SQL
我有一个 table 的形式:
User1 A
User2 A
User2 B
User3 C
User4 A
User4 C
User5 D
我需要从中选择仅出现过一次的用户。因此,例如,从上面我想要 User1、User3、User5。我可以使用 row_number()
之类的东西来删除重复项,但是这会 return 为所有用户排成一行,即使是那些拥有超过 1 个条目的用户,这不是我想要的。我也不能使用 DISTINCT
,因为例如 User2 A
和 User2 B
不会被捕获,因为它们不相等。
使用GROUP BY
:
select username
from t
group by username
having count(*) = 1;
如果您知道第二列中没有重复项,那么使用正确的索引可能会更快:
select t.*
from t
where not exists (select 1 from t t2 where t2.username = t.username and t2.col2 <> t.col2);
我有一个 table 的形式:
User1 A
User2 A
User2 B
User3 C
User4 A
User4 C
User5 D
我需要从中选择仅出现过一次的用户。因此,例如,从上面我想要 User1、User3、User5。我可以使用 row_number()
之类的东西来删除重复项,但是这会 return 为所有用户排成一行,即使是那些拥有超过 1 个条目的用户,这不是我想要的。我也不能使用 DISTINCT
,因为例如 User2 A
和 User2 B
不会被捕获,因为它们不相等。
使用GROUP BY
:
select username
from t
group by username
having count(*) = 1;
如果您知道第二列中没有重复项,那么使用正确的索引可能会更快:
select t.*
from t
where not exists (select 1 from t t2 where t2.username = t.username and t2.col2 <> t.col2);