mysql - 选择具有多个参数的 HAVING

标签 mysql sql database

我有users表和regulations表。

对于每个用户,每条规定有 4 行。

例如:user_id 1 接受了所有的规定,所以他在规定表中会有这样的记录:

  1. user_id = 1, regulation = 1, accepted = 1
  2. user_id = 1, regulation = 2, accepted = 1
  3. user_id = 1, regulation = 3, accepted = 1
  4. user_id = 1, regulation = 4, accepted = 1

现在我要做的是选择接受所有规定的所有用户。

不确定我应该如何构建此查询的 HAVING 部分。

这是我的看法,但我几乎可以肯定它是错误的,此外它说它没有看到 regulations.regulation 列:

SELECT users.* FROM users 
JOIN regulations ON regulations.user_id = users.id
GROUP BY regulations.user_id
HAVING
    (regulations.regulation = 1 AND regulations.accepted = 1)
and (regulations.regulation = 2 AND regulations.accepted = 1)
and (regulations.regulation = 3 AND regulations.accepted = 1)
and (regulations.regulation = 4 AND regulations.accepted = 1)

问题:在所有 4 条规定中选择所有接受 = 1 的用户的正确方法是什么?

最佳答案

您可以按如下方式进行:

SELECT users.id FROM users 
     INNER JOIN regulations ON regulations.user_id = users.id
WHERE regulations.accepted = 1
GROUP BY users.id
HAVING count(distinct regulations.regulation) = 4

它从 users 表中选择所有 users.id,其中接受的不同规则的数量为 4。'HAVING' 子句中的 count distinct 是为了确保如果相同的规则出现两次,则只计算一次. 它不检查接受的规定是否为 1、2、3 或 4 之一。

另一种使用嵌套查询而不是内部连接来达到相同效果的选项:

SELECT * from users u
WHERE 4 = ( SELECT count(distinct regulation) 
            FROM regulations r
            WHERE r.user_id=u.id and r.accepted=1 )

最后一个(确实取决于每个法规具有不同的值)没有 WHERE 或 HAVING 子句并且没有 COUNT:

SELECT u.* from users u
   INNER JOIN regulations r1 ON r1.user_id=u.id and r1.accepted=1 and r1.regulation=1
   INNER JOIN regulations r2 ON r2.user_id=u.id and r2.accepted=1 and r2.regulation=2
   INNER JOIN regulations r3 ON r3.user_id=u.id and r3.accepted=1 and r3.regulation=3
   INNER JOIN regulations r4 ON r4.user_id=u.id and r4.accepted=1 and r4.regulation=4

另见测试:Fiddle

关于mysql - 选择具有多个参数的 HAVING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51893247/

相关文章:

mysql - 为什么 mysql 服务器没有在 Solaris 10 上启动?

php - 为什么外来字符以一种时髦的方式保存到 MySQL 服务器?

mysql - SELECT 语句中的 MAX

mysql - 什么情况下外键不能为空?

mysql查询: selecting conditional status

MySQL:从列表中获取下一个最接近的值

java - 构建安卓应用 :I can sending data to database in localhost but not the same in online database

sql - 如何在Oracle SQL Developer中查询数据库名称?

c# - SQL Server 变量(最大)

php - 来自一个表的 SQL COUNT,其中另一表的条件为 true