查询每个购买数量的产品清单

时间:2013-09-10 08:55:29

标签: mysql

我的MySQL并不像其他人那么敏锐,我一直试图在过去一小时内解决这个问题。也许你可以指出我正确的方向。我有一份产品清单,我正试图从中获取报告。这就是我所拥有的:

-- Product list: tbl_products
id       product_name
------  ----------------
1        Hamburger
2        Cheeseburger
3        Burger Balls


-- List of orders: tbl_orders
id       created
------  -----------------------
23       2013-09-04 00:00:00
45       2013-09-05 00:00:00
67       2013-09-09 00:00:00


-- Products bought per order: tbl_product_orders
order_id    product_id      quantity
----------  --------------  --------
23          1                4
23          2                6
45          1                1
67          3                2

这是我想通过一个查询实现的目标:

-- How do I get this
order_id    Hamburger     Cheeseburger    Burger Balls
----------  ------------- --------------- --------------
23           4             6               0
45           1             0               0
67           0             0               2

有谁知道怎么做?

修改 我稍后会发布我之前的脚本。我现在必须跑到课堂上。 :)

2 个答案:

答案 0 :(得分:5)

您可以使用动态SQL

来完成
SET @sql = NULL;

SELECT GROUP_CONCAT(CONCAT('SUM(CASE WHEN product_id = ', id,
                           ' THEN quantity ELSE 0 END) `', product_name, '`'))
  INTO @sql
  FROM tbl_products;

SET @sql = CONCAT('SELECT order_id,', @sql,
                  '  FROM tbl_product_orders
                    GROUP BY order_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

输出:

| ORDER_ID | HAMBURGER | CHEESEBURGER | BURGER BALLS |
|----------|-----------|--------------|--------------|
|       23 |         4 |            6 |            0 |
|       45 |         1 |            0 |            0 |
|       67 |         0 |            0 |            2 |

这是 SQLFiddle 演示


为简化调用结束时的操作,可以将其包装到存储过程中

DELIMITER $$
CREATE PROCEDURE sp_report()
BEGIN
  SET @sql = NULL;

  SELECT GROUP_CONCAT(CONCAT('SUM(CASE WHEN product_id = ', id,
                             ' THEN quantity ELSE 0 END) `', product_name, '`'))
    INTO @sql
    FROM tbl_products;

  SET @sql = CONCAT('SELECT order_id,', @sql,
                    '  FROM tbl_product_orders
                      GROUP BY order_id');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

这是 SQLFiddle 演示

答案 1 :(得分:1)

这将有效,只有一个加入:

select order_id,
sum(if(product_orders.product_id=1, product_orders.quantity, 0)) as hamburglars,
sum(if(product_orders.product_id=2, product_orders.quantity, 0)) as cheese_burglars,
sum(if(product_orders.product_id=3, product_orders.quantity, 0)) as burglar_balls
from orders inner join product_orders on orders.id=product_orders.order_id
group by order_id