如何从具有唯一ID的行中获取id?

时间:2013-02-12 18:45:57

标签: 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。在上面的数据中,这只是customer_id 1.

如果代码都是他们自己的列,那么这将是一个简单的查询:SELECT DISTINCT customer_id FROM tablename WHERE code = A AND code = B。但是,我似乎无法在多行上制作它。

2 个答案:

答案 0 :(得分:4)

您可以将GROUP BY customer_idHAVING子句一起使用:

select customer_id
from yourtable
where code in ('A', 'B')
group by customer_id
having count(distinct code) = 2

请参阅SQL Fiddle with Demo

如果要从表中返回更多数据,则可以将查询扩展为:

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)

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

select customer_id
from tablename
where code in ('A', 'B')
group by customer_id
having count(*) > 1