[英]Select all records where ID appears once SQL
I have a table of the form: 我有一个表格的形式:
User1 A
User2 A
User2 B
User3 C
User4 A
User4 C
User5 D
and out of this I need to pick ONLY the users who appear once . 而且,我只需要选择出现一次的用户即可 。 So for example, from the above I want User1, User3, User5.
因此,例如,从上面我想要User1,User3,User5。 I could use something like
row_number()
to remove duplicates, however this would return one row for all users, even those who have more than 1 entry, which is not what I want. 我可以使用
row_number()
类的东西来删除重复项,但是这将为所有用户返回一行,即使那些条目超过1个的用户也是如此,这不是我想要的。 I can't use DISTINCT
either as for example User2 A
and User2 B
would not be caught as they are not equal. 我也不能使用
DISTINCT
,例如User2 A
和User2 B
不会被捕获,因为它们不相等。
Use GROUP BY
: 使用
GROUP BY
:
select username
from t
group by username
having count(*) = 1;
If you know there are no duplicates in the second column, then with the right indexes the following might be faster: 如果您知道第二列中没有重复项,那么使用正确的索引,以下操作可能会更快:
select t.*
from t
where not exists (select 1 from t t2 where t2.username = t.username and t2.col2 <> t.col2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.