返回列匹配集合中所有值的行

时间:2014-03-06 06:08:43

标签: mysql sql

我在mysql中有一个Table结构:

ID  USER_ID TYPE
1   1       B
2   3       B
3   4       B
4   3       C
5   3       D
6   4       C
7   4       D
8   3       B

小提琴链接:http://sqlfiddle.com/#!2/7df38f/1

我有一个要求就是让所有'USER_ID'都有'Type'作为B和C. 即我需要一个如下结果:

USER_ID
3
4

7 个答案:

答案 0 :(得分:1)

SELECT user_id, COUNT(*) cnt
FROM tablename
WHERE type IN ('B', 'C')
GROUP BY user_id
HAVING cnt = 2

DEMO

这假定user_id + type组合是唯一的。如果没有,您可以创建一个获得不同值的子查询:

SELECT user_id, COUNT(*) cnt
FROM (SELECT distinct user_id, type
      FROM tablename
      WHERE type IN ('B', 'C')) x
GROUP BY user_id
HAVING cnt = 2

DEMO

答案 1 :(得分:1)

试试这个

SELECT distinct firsttable.user_id
FROM t1 firsttable, t1 secondtable
WHERE firsttable.type ='B' and secondtable.type ='C'  and firsttable.user_id =secondtable.user_id

SQLFiddle Demo

答案 2 :(得分:1)

尝试此查询

SELECT group_concat(`type`) AS types,user_id 
FROM users 
WHERE `type` IN('B','C') 
group by user_id 
HAVING FIND_IN_SET('B',types)>0 && FIND_IN_SET('C',types)>0 

SQL小提琴http://sqlfiddle.com/#!2/8ef8e/2

答案 3 :(得分:0)

请根据您的需要进行修改:

select * from (select USER_ID from T1 where USER_ID IN 
(select USER_ID from T1 where T1.TYPE = 'B')) t
INNER JOIN  
((select USER_ID from T1 where USER_ID IN 
(select USER_ID from T1 where T1.TYPE = 'C'))) t2
on t.USER_ID = t2.USER_ID group by t.user_id

SQL FIDDLE

编辑:更好的方法

select * from (select USER_ID from T1 where T1.TYPE = 'B') t
INNER JOIN  
(select USER_ID from T1 where T1.TYPE = 'C') t2
on t.USER_ID = t2.USER_ID group by t.user_id

Sql fiddle

答案 4 :(得分:0)

SELECT user_id, count(*) cnt
FROM T1
WHERE type IN ('B', 'C')
GROUP BY user_id
HAVING cnt >= 2;

user_id cnt
3       3
4       2

答案 5 :(得分:0)

尝试以下SQL:

SELECT user_id, COUNT(*) cnt
FROM T1
WHERE type IN ('B', 'C')
GROUP BY user_id
HAVING cnt >= 2;

SQL Fiddle

答案 6 :(得分:-1)

select USER_ID from ( 
    ( select USER_ID from table where TYPE = 'B' ) as t1 join 
    ( select USER_ID from table where TYPE = 'C' ) as t2 on
    on t1.USER_ID = t2.USER_ID );