mysql根据字段值返回行数

时间:2013-04-17 20:05:02

标签: mysql counter

select id,name,total_copies from contacts.

这是select语句。因为它可以带回来

结果是

1,john,1
2,peter,3
3,sara,2

我需要它

1,john,1
2,peter,2
2,peter,2
2,peter,2
3,sara,2
3,sara,2

简而言之,如果total_copies = 3则必须返回该行3次,如果值为5则必须返回5次行等

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

SELECT contacts.*, n
FROM
  (SELECT n1.n*10+n2.n n FROM
  (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) n1,
  (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) n2) numbers
   INNER JOIN contacts ON contacts.total_copies>numbers.n
ORDER BY
  id

请参阅小提琴here。带数字的索引表应该使查询更容易和更快:

CREATE TABLE numbers (n int);    
INSERT INTO numbers VALUES (0), (1), (2), (3), (4), (5);

SELECT contacts.*
FROM numbers INNER JOIN contacts
     ON contacts.total_copies>numbers.n
ORDER BY id;

示例here