[英]How to select only the unique records
我的意思是留下任何重復的記錄
例如
ID NAME
1 a
2 a
3 b
4 b
5 c
所需的輸出。
僅5 c
我厭倦了嘗試這個。 所以我認為我沒有任何可粘貼的代碼。
這是一種方法:
select t.*
from table t
where not exists (select 1
from table t2
where t2.name = t.name and t2.id <> t.id
);
這是另一種方式:
select t.*
from table t join
(select name, count(*) as cnt
from table t
group by name
having cnt = 1
) tt
on tt.name = t.name;
這是另一種可能的方法:
select min(id), name from table group by name having count(*) = 1
我認為最干凈的方法是為每一行選擇名稱和ID,按名稱分組,並僅對COUNT(*)為1的值進行過濾。這意味着名稱不屬於任何行唯一的除外。
它看起來像這樣:
SELECT id, name
FROM myTable
GROUP BY name
HAVING COUNT(*) = 1;
我無法使SQL正常工作,但在MySQL工作台中對此進行了驗證:
這是另一種方法:
SELECT * FROM table AS A
WHERE (SELECT COUNT(*) FROM table AS T
WHERE T.NAME = A.NAME) = 1
select a.*
from table a
left join table b on a.name = b.name and a.id <> b.id
where b.id is null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.