mysql - mysql中使用count()和join时返回错误值
问题描述
我有两个表:表 A 和表 B:
表 A
+--------+----------+------------+
| cat_id | cat_name | is_deleted |
+--------+----------+------------+
| 1 | name 1 | 0 |
+--------+----------+------------+
| 2 | name 2 | 0 |
+--------+----------+------------+
| 3 | name 3 | 1 |
+--------+----------+------------+
表 B
+--------------+----------+--------+------------+
| event_cat_id | event_id | cat_id | is_deleted |
+--------------+----------+--------+------------+
| 1 | 13 | 2 | 0 |
+--------------+----------+--------+------------+
| 2 | 23 | 2 | 1 |
+--------------+----------+--------+------------+
| 3 | 3 | 2 | 0 |
+--------------+----------+--------+------------+
我需要从表 A 中检索所有记录,并从表 B 中获取每个 cat_id 的 event_id 数量,以便对上述值有以下结果:
"categories": [
{
"cat_name": "Name 1",
"is_deleted": "0",
"total_items": "0"
},
{
"cat_name": "Name 2",
"is_deleted": "0",
"total_items": "2"
}
]
到目前为止我没有成功的尝试如下:
SELECT TABLE_A.cat_name, TABLE_A.is_deleted,
COUNT(TABLE_B.cat_id) AS total_items
FROM TABLE_A LEFT JOIN TABLE_B ON (TABLE_A.cat_id = TABLE_B.cat_id)
WHERE TABLE_A.is_deleted = 0 AND TABLE_B.is_deleted = 0
GROUP BY TABLE_A.cat_name
此查询返回错误的值total_items
。为什么?
解决方案
TABLE_B.is_deleted = 0
在子句中设置条件ON
而不是WHERE
:
SELECT TABLE_A.cat_name, TABLE_A.is_deleted,
COUNT(TABLE_B.cat_id) AS total_items
FROM TABLE_A LEFT JOIN TABLE_B
ON (TABLE_A.cat_id = TABLE_B.cat_id) AND TABLE_B.is_deleted = 0
WHERE TABLE_A.is_deleted = 0
GROUP BY TABLE_A.cat_name
如果条件在WHERE
子句中,则将LEFT
连接转换为INNER
连接,从 中删除所有不匹配的行TABLE_B
。
请参阅演示。
结果:
| cat_name | is_deleted | total_items |
| -------- | ---------- | ----------- |
| name 1 | 0 | 0 |
| name 2 | 0 | 2 |
推荐阅读
- html - 为什么包含导入和脚本后数据表选项不起作用
- php - 当 mysqli_fetch_assoc 表达式仅被一个变量替换时,PHP 会给出无限的 While 循环
- google-cloud-platform - 通过 Stackdriver 使用 Grafana 进行 BigQuery 监控 - 某些指标没有数据(例如“上传的字节数”)
- docker - DockerFile 单行指令 vs 多行指令
- python - 'list' 对象不能用 silhouette_score 调用
- python-3.x - 在数据框中添加新列并根据条件将行值更新为其他列名称
- c# - ASP.NET core 错误处理错误信息
- c# - 为什么我在 Unity RayMarching 着色器中出现 for-loop 错误?
- html - 使用 igx-date-picker 格式化日期
- linux - 嵌套虚拟化(基于 KVM)构建灾难恢复解决方案