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)

谢谢!我正在做一个嵌套选择的选择,我知道必须有更好的方法。仅供参考,如果您想从表中返回更多数据,可以在存在的
中使用此选项。见我的编辑谢谢!我正在做一个嵌套选择的选择,我知道必须有更好的方法。仅供参考,如果您想从表中返回更多数据,可以在存在的
中使用此选项。查看我的编辑