Mysql return 每个计数一行
Mysql return one row per count
假设我有这样一个 table:
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
是否有针对每个计数的 return 一行的查询?如果计数为零,它应该 return 没有行。
应该return像这样:
CAR ID
Fusion 1
Fusion 1
Honda CRV 3
Toyota Camry 4
Toyota Camry 4
Toyota Camry 4
到目前为止,我已经尝试了自联接和交叉联接的各种组合。 None 成功了。
如果 table 中的 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
或者,您可以即时构建 "tally" table 以加入
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
您可以根据需要调整派生 table 生成的行数。这个特定的生成 100 行。
这是两个查询的 dbfiddle 演示
输出:
+--------------+----+
| car | id |
+--------------+----+
| Fusion | 1 |
| Honda CRV | 3 |
| Toyota Camry | 4 |
| Fusion | 1 |
| Toyota Camry | 4 |
| Toyota Camry | 4 |
+--------------+----+
假设我有这样一个 table:
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
是否有针对每个计数的 return 一行的查询?如果计数为零,它应该 return 没有行。
应该return像这样:
CAR ID
Fusion 1
Fusion 1
Honda CRV 3
Toyota Camry 4
Toyota Camry 4
Toyota Camry 4
到目前为止,我已经尝试了自联接和交叉联接的各种组合。 None 成功了。
如果 table 中的 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
或者,您可以即时构建 "tally" table 以加入
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
您可以根据需要调整派生 table 生成的行数。这个特定的生成 100 行。
这是两个查询的 dbfiddle 演示
输出:
+--------------+----+ | car | id | +--------------+----+ | Fusion | 1 | | Honda CRV | 3 | | Toyota Camry | 4 | | Fusion | 1 | | Toyota Camry | 4 | | Toyota Camry | 4 | +--------------+----+