2015-02-09 84 views
1

我有多個行選擇順序表所示:MySQL的:基於數量列

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的訂單...所以我不知道最大值。

有沒有更好的方法來做到這一點?

+0

請學習後15個職位格式化您的問題。 – 2015-02-09 11:31:30

回答

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

這可以通過使用數字表來完成,並且如果你沒有一個可以使用所描述的方法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