MySQL:选择多个基于数量列的行

时间:2015-02-09 11:29:22

标签: mysql multiple-columns

我有一个订单表,如:

product|quantity

示例:

bread|3

我需要一个选择:

row1- bread
row2- bread
row3- bread

我是这样做的:

SELECT product FROM (
     SELECT product FROM order WHERE quantity > 0 UNION ALL
     SELECT product FROM order WHERE quantity > 1 UNION ALL
     SELECT product FROM order WHERE quantity > 2 UNION ALL
     SELECT product FROM order WHERE quantity > 3
) s;

工作得很好。 但是他们告诉我最大数量是4。 现在我看到12,32的订单......所以我不知道最大值。

有更好的方法吗?

2 个答案:

答案 0 :(得分:5)

您需要一个可生成数字的表格。如果您的orders表有足够的行,则可以使用变量生成数字:

select product
from orders o join
     (select (@rn := @rn + 1) as n
      from orders o cross join (select @rn := 0) vars
     ) n
     on n.n <= o.quantity;

答案 1 :(得分:1)

这可以使用数字表来完成,如果您没有数字表,您可以使用this answer中描述的方法动态生成一系列数字。使用该方法,您可以运行如下查询:

-- set up test data
CREATE TABLE Table1 (product VARCHAR(20), quantity int);
insert into Table1 values ('bread',3), ('butter',5), ('milk',2);

-- set up views for number series
CREATE VIEW generator_16
AS SELECT 0 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   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL 
   SELECT 15;

CREATE VIEW generator_256
AS SELECT ( ( hi.n * 16 ) + lo.n ) AS n
     FROM generator_16 lo, generator_16 hi;

-- and the actual query
SELECT product, t.quantity, i.n
FROM Table1 t
JOIN generator_256 i 
ON i.n BETWEEN 1 AND t.quantity
ORDER BY t.product, i.n;

结果:

| PRODUCT | QUANTITY | N |
|---------|----------|---|
|   bread |        3 | 1 |
|   bread |        3 | 2 |
|   bread |        3 | 3 |
|  butter |        5 | 1 |
|  butter |        5 | 2 |
|  butter |        5 | 3 |
|  butter |        5 | 4 |
|  butter |        5 | 5 |
|    milk |        2 | 1 |
|    milk |        2 | 2 |

Sample SQL Fiddle