Mysql每个计数返回一行

时间:2017-06-16 23:48:45

标签: mysql sql unpivot

我们说我有这样一张桌子:

CREATE TABLE `car2` (
    `id` INT(11) NOT NULL,
    `car` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `count` INT(3) UNSIGNED NULL DEFAULT '0',
    PRIMARY KEY (`id`)
);

有了这些数据:

ID    CAR            COUNT
1     Fusion         2
2     Tesla Model 3  0
3     Honda CRV      1
4     Toyota Camry   3

是否有查询为每个计数返回一行?如果计数为零,它应该不返回任何行。

应该返回这样的内容:

CAR           ID
Fusion        1
Fusion        1
Honda CRV     3
Toyota Camry  4
Toyota Camry  4
Toyota Camry  4

到目前为止,我已尝试过各种自我和CROSS JOINS的组合。没有人工作过。

1 个答案:

答案 0 :(得分:2)

如果表中的id值从1开始单调递增,并且最大count值小于总行数,那么您只需执行

SELECT s.car, s.id
  FROM car2 s JOIN car2 t
    ON t.id BETWEEN 1 AND s.count
 ORDER BY car

或者,您可以即时构建“计数”表以加入

SELECT car, id
  FROM car2 s 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
  ) t
    ON n BETWEEN 1 AND s.count
 ORDER BY car

您可以根据需要调整派生表生成的行数。这个特定的行生成100行。

以下是两个查询的dbfiddle演示

输出:

+--------------+----+
| car          | id |
+--------------+----+
| Fusion       |  1 |
| Honda CRV    |  3 |
| Toyota Camry |  4 |
| Fusion       |  1 |
| Toyota Camry |  4 |
| Toyota Camry |  4 |
+--------------+----+