![](/img/trans.png)
[英]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.