我在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
答案 0 :(得分:1)
SELECT user_id, COUNT(*) cnt
FROM tablename
WHERE type IN ('B', 'C')
GROUP BY user_id
HAVING cnt = 2
这假定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
答案 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
答案 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
答案 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
编辑:更好的方法
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
答案 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;
答案 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 );