Mysql 同组查询
Mysql query with group
我有以下 table:
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
我想select俱乐部(club_id)有两个选项(2和3)
我没有得到以下查询的任何结果:
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
函数中的项目数。
我有以下 table:
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
我想select俱乐部(club_id)有两个选项(2和3)
我没有得到以下查询的任何结果:
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
函数中的项目数。