我正在做一个项目,并陷入了困境。问题是我有以下两个表:
1. users :
+----+------+
| id | name |
+----+------+
| 1 | ABC |
| 2 | XYZ |
| 3 | JKL |
+----+------+
2. user_mistakes :
+----+---------+-------------+--------+
| id | user_id | mistake | status |
+----+---------+-------------+--------+
| 1 | 1 | Lorem ipsum | 1 |
| 2 | 1 | Lorem ipsum | 1 |
| 3 | 2 | Lorem ipsum | 0 |
| 4 | 2 | Lorem ipsum | 1 |
+----+---------+-------------+--------+
user_mistakes
。status
在 0 =待审核和1 =已批准
根据上述users
和user_mistakes
表数据,我希望每个用户的未决和批准状态计数如下:
+---------+------+------------------+-------------------+
| user_id | name | pending_mistakes | approved_mistakes |
+---------+------+------------------+-------------------+
| 1 | ABC | 0 | 2 |
| 2 | XYZ | 1 | 1 |
| 3 | JKL | 0 | 0 |
+---------+------+------------------+-------------------+
有什么方法可以通过单个查询实现?
谢谢
答案 0 :(得分:1)
您可以尝试以下代码:
SELECT
users.id,users.name,
SUM(IF(mistakes.status=1, 1, 0)) AS approved_mistakes,
SUM(IF(mistakes.status=0, 1, 0)) AS pending_mistakes
FROM users
LEFT JOIN mistakes ON mistakes.user_id = users.id
GROUP BY mistakes.user_id
让我知道您是否遇到任何问题
答案 1 :(得分:0)
选择待处理的错误,并根据未处理的错误从user_mistakes组中计数(待处理的错误)