join two tables along with count of records from second table based on condition(根据条件连接两个表以及第二个表中的记录数)
问题描述
我有以下表格 -
这里是SQLFIDDLE
类别
+-----------+-------------+
| column | type |
+-----------+-------------+
| id | int(11) |
| name | varchar(40) |
| unit | varchar(50) |
| is_active | tinyint(1) |
+-----------+-------------+
和
产品
+-------------+---------------+
| column | type |
+-------------+---------------+
| id | int(11) |
| category_id | int(11) |
| name | varchar(40) |
| base_rate | decimal(10,2) |
| is_active | tinyint(1) |
+-------------+---------------+
我想获取类别列表以及活动产品的数量.如果某个类别没有有效的产品,则应返回 0.
I want to get list of categories along with count of number of products active. If no products are active for a category it should return 0.
有点像下表 -
+----+--------+--------------+
| id | name | active_count |
+----+--------+--------------+
| 1 | Steel | 1 |
| 2 | Cement | 2 |
+----+--------+--------------+
我想出了以下查询 -
I have come up with following query -
SELECT c.id, c.name, c.unit, COUNT(p.category_id) as active_count
FROM `categories` c
JOIN `products` p
ON c.id = p.category_id
WHERE ( p.is_active = 1 )
GROUP BY p.category_id;
上述查询仅在每个类别中至少有一个产品处于活动状态时有效.如果没有可用的产品,则应将 active_count 返回为 0
This above query works only when there is at least one product active in each of category. If there are not products available it should return active_count as 0
我该如何解决这个问题?
How can I fix this ?
这里是SQLFIDDLE
推荐答案
使用LEFT JOIN代替INNER JOIN:
SELECT c.id, c.name, c.unit, COUNT(p.category_id) as active_count
FROM `categories` c
LEFT JOIN `products` p
ON c.id = p.category_id AND p.is_active = 1
GROUP BY c.id;
将谓词 p.is_active = 1 从 WHERE 子句移动到 ON 也很重要,这样 all查询返回categories表的em>条记录.
It is also important to move predicate p.is_active = 1 from WHERE clause to ON, so that all records of categories table are returned by the query.
这篇关于根据条件连接两个表以及第二个表中的记录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据条件连接两个表以及第二个表中的记录数
基础教程推荐
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
