好的。我有一个看起来像这样的查询:

SELECT
    SUM(`order_items`.`quantity`) as `count`,
    `menu_items`.`name`
FROM
    `orders`,
    `menu_items`,
    `order_items`
WHERE
    `orders`.`id` = `order_items`.`order_id` AND
    `menu_items`.`id` = `order_items`.`menu_item_id` AND
    `orders`.`date` >= '2008-11-01' AND
    `orders`.`date` <= '2008-11-30'
GROUP BY
    `menu_items`.`id`

此查询的目的是显示给定日期范围内售出的商品数量。尽管这有效,但如果特定项目在日期范围内没有销售,我现在需要它显示 count0。我尝试在 COALESCE 周围使用 SUM 但这并没有奏效,我真的没想到会这样。无论如何,有谁知道我将如何实现这一目标?我有这样的时刻之一,我觉得我应该知道这一点,但我想不出来。

干杯

最佳答案

如果将日期条件放在 JOIN 子句中,则无需任何子查询即可完成此操作。

下面是我在 MySQL 5.0 上测试的代码。

SELECT m.name, COALESCE(SUM(oi.quantity), 0) AS count
FROM menu_items AS m
  LEFT OUTER JOIN (
    order_items AS oi JOIN orders AS o
      ON (o.id = oi.order_id)
  ) ON (m.id = oi.menu_item_id
      AND o.`date` BETWEEN '2008-11-01' AND '2008-11-30')
GROUP BY m.id;

输出:
+--------+-------+
| name   | count |
+--------+-------+
| bread  |     2 |
| milk   |     1 |
| honey  |     2 |
| cheese |     0 |
+--------+-------+

这是 MySQL 风格的 DDL 和设置代码:
DROP TABLE IF EXISTS menu_items;
CREATE TABLE menu_items (
  id            INT PRIMARY KEY,
  name          VARCHAR(10)
) TYPE=InnoDB;

DROP TABLE IF EXISTS orders;
CREATE TABLE orders (
  id            INT PRIMARY KEY,
  `date`        DATE
) TYPE=InnoDB;

DROP TABLE IF EXISTS order_items;
CREATE TABLE order_items (
  order_id      INT,
  menu_item_id  INT,
  quantity      INT,
  PRIMARY KEY (order_id, menu_item_id),
  FOREIGN KEY (order_id) REFERENCES orders(id),
  FOREIGN KEY (menu_item_id) REFERENCES menu_items(id)
) TYPE=InnoDB;

INSERT INTO menu_items VALUES
  (1, 'bread'),
  (2, 'milk'),
  (3, 'honey'),
  (4, 'cheese');

INSERT INTO orders VALUES
  (1, '2008-11-02'),
  (2, '2008-11-03'),
  (3, '2008-10-29');

INSERT INTO order_items VALUES
  (1, 1, 1),
  (1, 3, 1),
  (2, 1, 1),
  (2, 2, 1),
  (2, 3, 1),
  (3, 4, 10);

关于sql - 联合总和集团?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/263816/

10-11 02:38