我有下表:
id club_id club_option_id created
---|-------|--------------|-------
1 | 1 | 2 | 2015-02-11 16:31:23
2 | 1 | 3 | 2015-02-11 16:31:23
3 | 2 | 2 | 2015-03-06 08:16:02
我想选择有两个选项(2 和 3)的俱乐部 (club_id)
我没有得到以下查询的任何结果:
SELECT club_id FROM
club_options_to_clubs
WHERE club_option_id = 2 AND club_option_id = 3
GROUP BY club_id
结果如何得到 club_id 1?
最佳答案
你可以这样做 -
select
t1.club_id from table_name t1
where t1.club_option_id = 2
and exits (
select 1 from table_name t2
where t1.club_id = t2.club_id
and t2.club_option_id = 3
)
另一种方式是
select club_id from table_name
where club_option_id in (2,3)
group by club_id
having count(*) = 2
使用上述方法,如果您需要检查多个 club_option_id
,将它们传递到 in
函数中,然后使用 having count(*) = n 中的数字
这里 n = in
函数中的项目数。
关于带组的Mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28894234/