mysql - 如何将 o 值结果包含在 COUNT 中? SQL查询

标签 mysql sql

我需要计算守门员的封堵次数。我有两个表(“玩家”和“游戏统计”)。当守门员“着装”(有比赛)时,当守门员在“goalsagainst”列中没有“0”/零值时,我在获取值时遇到问题。 因此,当“dressed”列的值为 1 作为“shutout”列时,我需要计算“goalsagainst”列中的所有零值。如果“goalsagains”列中的值大于 0,“shutout”列值应为 0;

我尝试了类似主题中的其他解决方案,但总是得到相同的结果,即仅计算零值而不会显示其他值。

My structure:
players
|p_id|pos|
--------
| 1 | G |
--------
| 2 | D |
--------
| 3 | O |
--------
| 4 | G |

stats
|g_id|p_id|goalsagainst|dressed|
--------------------------------
|  1 |  1 |    2       |  1    |
--------------------------------
|  1 |  4 |    0       |  0    |
--------------------------------
|  1 |  3 |    NULL    |  1    |
--------------------------------
|  1 |  2 |    NULL    |  1    |
--------------------------------
|  2 |  1 |    0       |  0    |
--------------------------------
|  2 |  4 |    0       |  1    |
--------------------------------
|  2 |  3 |    NULL    |  1    |
--------------------------------
|  2 |  2 |    NULL    |  1    |
   SELECT 
      stats.id,
      COUNT(stats.goalsagainst) AS shutouts 
   FROM `stats` 
      RIGHT JOIN players 
      ON stats.id = players.id
   WHERE goalsagainst = 0 
      AND players.pos = 'G' 
      AND stats.dressed = 1 
      GROUP BY stats.id;

my result is:

p_id|shutouts
-------------
 4  |    1    

when it should be:

p_id|shutouts
-------------
 1  |    0    
-------------
 4  |    1

最佳答案

您的问题是 WHERE 子句中 stats 表上的条件有效地将 RIGHT JOIN 转换为 INNER JOIN 。要解决此问题,请将条件移至 ON 子句。其次,您需要在SELECTGROUP BY中使用players.p_id,因为stats.p_id可能是NULL:

SELECT players.p_id,
       COUNT(stats.goalsagainst) AS shutouts 
FROM `stats` 
RIGHT JOIN players ON stats.p_id = players.p_id AND stats.dressed = 1 AND stats.goalsagainst = 0 
WHERE players.pos = 'G' 
GROUP BY players.p_id;

输出:

p_id    shutouts
1       0
4       1

Demo on dbfiddle

关于mysql - 如何将 o 值结果包含在 COUNT 中? SQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57867047/

相关文章:

MySQL 将行转为动态数量的列

php - 我的网站 (PHP) 上的赌博应用程序出现问题

php - 为什么插入不起作用

mysql - 尝试通过检查条件使用单个插入语句插入不同的结果集

c# - 存储过程不返回值 - C#

mysql - 根据唯一用户名计算记录数

php - MySQL - 返回两个日期/时间之间的行

PHP - 根据 mysql 行结果显示不同的图像

python - 可以自动将数据从 memcached 传输到 mysql DB 吗?

mysql - 如何找出mysql中加载文件功能中哪一行被破坏