[英]Mysql: how to select rows where the combination of 2 of the column values are unique given a certain other column value
[英]How to only select rows where one column is unique and the other is a certain value
我想弄清楚哪些 ID 只有一種類型的交易。
我試過加入並選擇不同的但我做錯了
select transactions.type, id
from datasource
group by id, transactions.type
這給了我一個包含兩種事務類型的表:dep 或withdraw。 大多數ID有兩行,一是dep,另一行是withdraw。 我只想選擇只有提款交易類型的 ID
使用 where 條件和not exists
select transactions.type, id from datasource t1
where type='withdraw'
and not exists( select 1 from datasource t2 where t1.id=t2.id
and type='dep')
您可以將group by
與having count(*)=1
子句一起使用
select id
from datasource
where transactions_type in
(
select transactions_type, id
from datasource
group by transactions_type
having count(*)=1 )
由於“您正在嘗試找出哪些 ID 只有一種類型的交易”
如果您專門查找transactions_type = 'withdraw'
,則將and transactions_type = 'withdraw'
到上述 Select 語句的末尾。
PS 我想transactions.type
有一個類型,應該是transactions_type
,不是嗎?
我認為聚合可以滿足您的需求。 但是,我很困惑你的數據結構是什么。 某處需要join
:
select ds.id, min(t.type)
from datasource ds join
transactions t
on ds.? = t.? -- what is the join key?
group by ds.id
having min(t.type) = max(t.type);
如果transactions.type
實際上是datasource
一列,則:
select ds.id, min("transactions.type")
from datasource ds
group by ds.id
having min("transactions.type") = max("transactions.type");
與其他答案類似,但更簡單:
select id, count(distinct transactions.type)
from datasource
group by id
having count(distinct transactions.type) = 1
然而,不清楚transactions.type 是什么。 它似乎作為列名無效。 或者你的意思是寫transactions_type
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.