带组的Mysql查询

标签 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?

最佳答案

你可以这样做 -

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/

相关文章:

mysql - 修复PHPBB DB损坏时可以使用哪些好的技巧和工具?

php - 检查输入的开始和结束日期是否在数据库中已有的开始和结束日期之间

php - 尝试更新 ps_pagination 类

python - Pandas 集团 : How to get top n values based on a column

PHP - 搜索数据库并在同一页面上返回结果

php - 在单行中按名称对列组的值进行计数

按月分组的 SQL 结果

r - 使用来自包 `modifiedmk` 的统计信息在 R 中创建汇总表

mysql - 为什么此代码能够在 HAVING 中使用来自 SELECT 的别名?

php - 修复简单的 PHP WordPress 用户显示名称脚本