mysql - 如果条件不匹配则返回 0
问题描述
我有一个足球比赛,人们可以预测比赛。如果他们认为主队获胜,他们可以给比赛打 1,如果客队获胜,打 2,如果平局打 3。如果他们正确地预测了一场比赛,他们就会得到一分。我的数据库中的表如下所示:
表匹配
| id | home | away | result | round_id
| --- | ---------| -------- -| -------|----------|
| 1 | id club 1| id club 2 | 1 | id round 1
| 2 | id club 5| id club 4 | 3 | id round 1
| 3 | id club 8| id club 5 | 1 | id round 2
Table predictions
| prediction | user_id | match_id |
| -------- | -------------- | -------- |
| 1 | id user 1 | id match 1
| 3 | id user 1 | id match 2
| 2 | id user 1 | id match 3
最初我想在 PHP 中计算分数,但我认为这也应该只能通过 MySQL 来实现。所以我尝试了一些方法并提出了以下查询:
SELECT Count(*) AS points,
username,
round_id
FROM predictions
LEFT JOIN matches
ON predictions.match_id = matches.id
INNER JOIN users
ON predictions.user_id = users.id
WHERE predictions.prediction = matches.result
GROUP BY username,
round_id
ORDER BY points DESC,
username ASC
该查询正确计算每个用户每轮的得分,唯一的问题是,如果参与者在游戏轮中没有任何权利,则它根本不会出现在列表中。有没有人知道如果他们有 0 分,该怎么做才能让参与者也加入列表?转换为上面提到的表,第 2 轮将不会返回查询,因为其中的唯一匹配项被错误预测。但是,我确实想要这个,因此第 2 轮返回的分数为 0。
我想要的结果:
| points | username | round_id|
| -------- | -------------- | --------|
| 2 | John | 1
| 0 | John | 2
结果我现在:
| points | username | round_id|
| -------- | -------------- | --------|
| 2 | John | 1
解决方案
WHERE
条款:
WHERE predictions.prediction = matches.result
过滤掉任何错误的预测,但即使你删除它,聚合函数COUNT(*)
也会计算错误的预测。
像这样加入和分组:
SELECT SUM(p.prediction = m.result) AS points,
u.username,
m.round_id
FROM users u
INNER JOIN predictions p ON p.user_id = u.id
INNER JOIN matches m ON m.id = p.match_id
GROUP BY u.id, u.username, m.round_id
ORDER BY points DESC, u.username ASC;
聚合函数将对被评估为for和forSUM()
的布尔表达式求和。prediction = result
1
true
0
false
请参阅演示。
推荐阅读
- c++ - to_string().length() 在 c++ 中给出不正确的结果。谁能解释一下这种行为?
- unity3d - 我可以仅通过 python 经验学习 Unity 吗?
- python - 将数据列写入 txt 文件中的行/行
- java - Rabin Karp 算法运行速度比 naive 慢
- c# - 使用 Polly httpClient ConfigureAwait(true) 重试模式
- python - 我在 python 中的文件和目录上测试模块时遇到问题
- reactjs - React 联系表单中的 CORS 错误 Firebase 云函数
- r - 根据不同图表上的类型制作图表
- r - 给定这个循环组的生成器,我如何构造一个矩阵?
- java - 我在这里遇到了 Arraylist 的问题,它覆盖了我添加到 Arraylist 中的 evreything 的最后一个对象(称为“Queen”)