gpt4 book ai didi

mysql - 查询每个商品的购买数量列表

转载 作者:行者123 更新时间:2023-11-29 04:08:57 25 4
gpt4 key购买 nike

我的 MySQL 不如其他的那么敏锐,在过去的一个小时里我一直在努力解决这个问题。也许你能给我指出正确的方向。我有一份产品 list ,我正试图从中获取一份报告。这是我的:

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

有人知道怎么做吗?

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

最佳答案

你可以用动态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 |

Here is SQLFiddle demo


To simplify things on calling end you can wrap it into a stored procedure

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 演示

关于mysql - 查询每个商品的购买数量列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18714547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com