当前位置:  开发笔记 > 后端 > 正文

COALESCE SUM GROUP?

如何解决《COALESCESUMGROUP?》经验,为你挑选了1个好方法。

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

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但没有做到这一点,我并没有真正期待它.无论如何,有谁知道我将如何实现这一目标?我有其中一个时刻,我觉得我应该知道这一点,但我想不出来.

干杯



1> Bill Karwin..:

如果将日期条件放在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);

推荐阅读
吻过彩虹的脸_378
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有