首页 > 解决方案 > 如果条件不匹配则返回 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 

标签: mysqljoingroup-bysumwhere-clause

解决方案


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 = result1true0false

请参阅演示


推荐阅读