1

我的 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

有谁知道如何做到这一点?

编辑: 稍后我会发布我早期的脚本。我现在只需要跑去上课。:)

4

2 回答 2

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 | 汉堡 | 芝士汉堡 | 汉堡球 |
|---------|------------|--------------|----------- ---|
| 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演示

于 2013-09-10T09:03:43.880 回答
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
于 2013-09-10T09:06:03.087 回答