我有一个由两个表组成的数据库:
categories
products
这两个表之间是一对多的关系,因此每个产品都可以链接到一个且只有一个类别为“category_id”的列。
产品类别有一个名为“status”的列。
这是我的问题: 我想返回所有类别,并在结果表中附加两列。
1)第一列将计算该类别中的产品数量。 (解决)
2)第二栏将计算产品的数量.'status'=“在售”。
到目前为止我的代码(不起作用!):
SELECT a.*, COUNT(b.`category_id`) AS product_count, COUNT(c.`category_id`) AS status_count
FROM `categories` AS a
LEFT JOIN `products` AS b ON ( b.`category_id` = a.`id` )
LEFT JOIN `products` AS c ON ( c.`status` = 'on sale' AND c.`category_id` = a.`id`)
GROUP BY a.`id`
ORDER BY a.`name` ASC;
以下代码仅返回产品计数列(有效!):
SELECT a.*, COUNT(b.`category_id`) AS equation_count
FROM `categories` AS a
LEFT JOIN `products` AS b ON ( b.`category_id` = a.`id` )
GROUP BY a.`id`
ORDER BY a.`name` ASC;
谢谢, 尼古拉::)
答案 0 :(得分:1)
无需额外JOIN
。您可以使用CASE
表达式来获取每个类别的status ='on sale'的产品数量。类似的东西:
SELECT
a.id,
a.name,
COUNT(b.`category_id`) AS product_count,
SUM(CASE WHEN b.status = 'on sale' THEN 1 ELSE 0 END) AS status_count
FROM `categories` AS a
LEFT JOIN `products` AS b ON b.`category_id` = a.`id`
GROUP BY a.`id`, a.name
ORDER BY a.`name` ASC;
由于您使用的是MySQL,因此可以使用SUM(b.status = 'on sale')
。这是因为在MySQL中将boolean隐式转换为0和1,IFNULL
将null
替换为0,对于那些在products表中没有条目的类别:
SELECT
a.id,
a.name,
COUNT(b.`category_id`) AS product_count,
IFNULL(SUM(b.status = 'on sale'), 0) AS status_count
FROM `categories` AS a
LEFT JOIN `products` AS b ON b.`category_id` = a.`id`
GROUP BY a.`id`, a.name
ORDER BY a.`name` ASC;