0

我有一个由两个表组成的数据库:

categories
products

这两个表之间是一对多的关系,因此每个产品都可以通过“category_id”列链接到一个且只有一个类别。

产品类别有一个名为“状态”的列。

这是我的问题:我想返回所有类别并将两列附加到结果表中。

1)第一列将统计该类别中的产品数量。(解决了)

2) 第二列将计算 products.'status'="on sale" 的产品数量。

到目前为止我的代码(不起作用!):

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;

谢谢,尼古拉 :)

4

1 回答 1

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;

SQL 小提琴演示


由于您使用的是 MySQL,因此您可以使用SUM(b.status = 'on sale'). 这是因为在 MySQL 中将布尔值隐式转换为 0 和 1,对于 products 表中没有条目的那些类别,用 0IFNULL替换:null

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;

更新的 SQL Fiddle 演示

于 2013-03-15T12:35:58.380 回答