MySQL按行数返回结果

时间:2014-03-10 03:54:03

标签: mysql

我需要一个查询,要求我返回类似下面的内容。

data table
--------------------------------
product name | quantity
apple        | 3
egg          | 2

query expected result
--------------------------------
product name
apple
apple
apple
egg
egg

感谢您的反馈

更新#1 好吧,我的坏问题不清楚。我希望通过按数量循环我的产品来显示我的结果。可能我对数量的预期结果会产生一些混乱。因此,是否可以在mysql中按数量循环我的记录?

1 个答案:

答案 0 :(得分:1)

如果你真的需要在SQL中使用它,你可以利用一个计数(数字)表,你可以创建并填充值1-100,如此

CREATE TABLE tally(n INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
INSERT INTO tally (n)
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 product_name
  FROM data_table d JOIN tally t
    ON t.n <= d.quantity

注意:确保MAX(n)tally表&gt; = MAX(quantity)中的data_table值为{{1}}适当

输出:

+--------------+
| product_name |
+--------------+
| apple        |
| apple        |
| apple        |
| egg          |
| egg          |
+--------------+

这是 SQLFiddle 演示