[英]MySQL Select distinct rows with same id with different value in a column and excluded a specific value in another column
我有一個MySQL數據庫表,如下所示:
id task_id users
1 1 1
1 2 2
2 1 2
2 2 1
2 10 1
3 1 2
3 2 2
3 3 2
4 1 2
我想選擇擁有多個用戶的id。 在這種情況下,用戶1和2有效。 但問題是,除了上述條件之外,我還想選擇那些沒有task_id = 10的人 。 所以最終輸出應該是id = 1。
但是無法實現排除task_id = 10的結果,因為嘗試使用以下查詢,它仍然顯示用戶1和2。
select distinct t.id
from table as t
join (
select id
from table
group by id
having count(distinct users) > 1
) as t2
on t.id = t2.id
AND task_id != 10
只需使用聚合和having
;
select id
from t
group by t
having count(distinct user) > 1 and
sum(task_id = 10) = 0;
如果你想要原始行,我會用exists
來表達它:
select t.*
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.task_id = 10) and
exists (select 1 from t t2 where t2.id = t.id and t2.user <> t.user);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.