问题描述
我有以下表格-
这里是 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 |
+----+--------+--------------+
我提出了以下查询-
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
我该如何解决?
这里是 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
也很重要,以便查询返回categories
表的 all 条记录.
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.
这篇关于根据条件将两个表以及第二个表中的记录数联接在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!