在一个

时间:2018-02-21 16:00:56

标签: 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;

但我想回复这样的内容:user idtotalfailures ...全部在一个查询中!

2 个答案:

答案 0 :(得分:3)

这可以通过条件聚合来完成。 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;

答案 1 :(得分:1)

作为一个注释,您可以简化查询,因为(大概)不需要user表:

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

您的查询给出了正确的答案,但您可能还需要注意NULL值。如果这是一个问题,请使用<=> NULL - 安全等值运算符:

SELECT a.user_id,
       SUM(s.status = 'CALCULATED') as num_calc,
       SUM(NOT s.status <=> 'CALCULATED') AS num_notcalc 
FROM scores s INNER JOIN
     accounts a
     ON s.account_id = a.id
GROUP BY a.user_id;