mysql - 将两个不同的 WHERE 子句/条件合并为一个查询

标签 mysql sql

我有三个表:usersaccountsscores。每个查询实际上都给了我想要的结果:

-- This will return all user ids with a count of "calculated" scores
SELECT u.id AS user_id, count(1) AS total FROM scores s
  INNER JOIN accounts a ON s.account_id = a.id
  INNER JOIN user u ON a.user_id = u.id
WHERE s.status = 'CALCULATED'
GROUP BY user_id;

-- This will return all user ids with a count of non-calculated scores
SELECT u.id AS user_id, count(1) AS failures FROM scores s
  INNER JOIN accounts a ON s.account_id = a.id
  INNER JOIN user u ON a.user_id = u.id
WHERE s.status <> 'CALCULATED'
GROUP BY user_id;

但我想返回类似这样的内容:用户 id总计失败...全部在一个查询中!

最佳答案

这可以通过条件聚合来完成。 SUM 中的条件根据满足的条件返回 1 或 0。

SELECT u.id AS user_id,
SUM(s.status='CALCULATED'),
SUM(s.status<>'CALCULATED') AS total 
FROM scores s
INNER JOIN accounts a ON s.account_id = a.id
INNER JOIN user u ON a.user_id = u.id
GROUP BY u.id;

关于mysql - 将两个不同的 WHERE 子句/条件合并为一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910291/

相关文章:

java - 连接到数据库时出现问题。 Java/SQLite

java - 我可以在 JPA 2 的 native 查询中有多个语句吗

php - 使用 html 复选框和 PHP 更改 MySQL TINYINT(1)

MySQL 按同级表中的匹配项数量排序

php - 显示两个表中的数据

sql - 主聚集键默认顺序是升序的吗?

mysql - 哪些点使sql查询更快

php - 数据库中未创建表

mysql - 如何按日期分组,考虑时区和 DST?

mysql - SQL查询以查找最近的记录是否都是同一类型