Mysql 如何从具有唯一id的行中获取id?
我有一张这样的桌子:Mysql 如何从具有唯一id的行中获取id?,mysql,entity-attribute-value,Mysql,Entity Attribute Value,我有一张这样的桌子: id | customer_id | code ----------------------- 1 | 1 | A 2 | 1 | B 3 | 2 | A 4 | 2 | D 5 | 3 | B 6 | 3 | C 6 | 3 | D 我需要一个SQL查询,返回代码等于A和B的所有客户id。在上面的数据中,这只能是客户i
id | customer_id | code
-----------------------
1 | 1 | A
2 | 1 | B
3 | 2 | A
4 | 2 | D
5 | 3 | B
6 | 3 | C
6 | 3 | D
我需要一个SQL查询,返回代码等于A和B的所有客户id。在上面的数据中,这只能是客户id 1
如果每个代码都是它们自己的列,这将是一个简单的查询:
从tablename中选择DISTINCT customer\u id,其中code=a和code=B
。然而,我似乎无法在多行上制作它 您可以将按客户id分组
与HAVING
子句一起使用:
select customer_id
from yourtable
where code in ('A', 'B')
group by customer_id
having count(distinct code) = 2
看
如果要从表中返回更多数据,可以将查询扩展到:
select *
from yourtable t1
where exists (select customer_id
from yourtable t2
where code in ('A', 'B')
and t1.customer_id = t2.customer_id
group by customer_id
having count(distinct code) = 2)
请参见您可以将
分组按客户id
与HAVING
子句一起使用:
select customer_id
from yourtable
where code in ('A', 'B')
group by customer_id
having count(distinct code) = 2
看
如果要从表中返回更多数据,可以将查询扩展到:
select *
from yourtable t1
where exists (select customer_id
from yourtable t2
where code in ('A', 'B')
and t1.customer_id = t2.customer_id
group by customer_id
having count(distinct code) = 2)
见谢谢!我正在做一个嵌套选择的选择,我知道必须有更好的方法。仅供参考,如果您想从表中返回更多数据,可以在存在的
中使用此选项。见我的编辑谢谢!我正在做一个嵌套选择的选择,我知道必须有更好的方法。仅供参考,如果您想从表中返回更多数据,可以在存在的中使用此选项。查看我的编辑