为每个“数量”选择一行'

时间:2014-06-17 11:50:38

标签: mysql

表:

Article | Quantity | pricePerUnit | order_id | article_id
--------|----------|--------------------------------------
     14 |        2 |        10.0  |        1 |    1
     X1 |        1 |         5.0  |        1 |    2

预期产出:

Article | Quantity | pricePerUnit | order_id
--------|----------|------------------------
     14 |        1 |        10.0  |     1
     14 |        1 |        10.0  |     1
     X1 |        1 |         5.0  |     1

对于每篇文章的每个数量,使用1行填充结果集的快速SELECT是什么?

抱歉,我没有尝试任何事情,我不确定这是否可行。自我加入..不会是一个帮助,分组功能,..

也许GROUP BY order_id, article_id, quantity以某种方式......

1 个答案:

答案 0 :(得分:2)

更新:对于的最大数量,只需执行

SELECT Article, 1 Quantity, pricePerUnit, order_id
  FROM articles a JOIN 
(
   SELECT 1 AS n UNION ALL 
   SELECT 2 UNION ALL 
   SELECT 3
) n
    ON n.n <= a.Quantity
 ORDER BY order_id, Article

这是 SQLFiddle 演示


原始回答:您可以尝试

SELECT Article, 1 Quantity, pricePerUnit, order_id
  FROM articles a JOIN 
(
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
) n
    ON n.n <= a.Quantity
 ORDER BY order_id, Article

内部选择返回100行,这意味着您可以将数量取消转换为值100.如果您需要更多,请相应更新。

这是 SQLFiddle 演示


鉴于它是一个报告,你有权创建一个新表,最好用一个你可以用相同方式创建的计数(数字)表替换内部选择:

CREATE TABLE tally (n int not null auto_increment primary key);
INSERT INTO tally
SELECT a.N + b.N * 10 + 1 n
  FROM 
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
ORDER BY n;

然后您的查询将显示为

SELECT Article, 1 Quantity, pricePerUnit, order_id
  FROM articles a JOIN tally n
    ON n.n <= a.Quantity
 ORDER BY order_id, Article

这是 SQLFiddle 演示