Mysql查询与组

时间:2015-03-06 07:46:33

标签: mysql group-by

我有下表:

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?

1 个答案:

答案 0 :(得分: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_idin函数中传递它们,然后使用having count(*) = n中的数字 这里n = in函数中的项目数。