如何在 mysql 中将单行拆分为多行

how to split single row to multiple rows in mysql

我想在 mysql 中将每一行分成两行(我想用逗号将 num1 和 num2 分成两行)。我的数据是这样的:

datetime1               count    num1    num2
2022-03-16 03:00:00     0        0,1     1,2
2022-03-16 04:00:00     0        0,1     1,2

现在我想要这样的数据:

datetime1                count    num1 num2
2022-03-16 03:00:00      0        0    1
2022-03-16 03:00:00      0        0    2
2022-03-16 03:00:00      0        1    1
2022-03-16 03:00:00      0        1    2
2022-03-16 04:00:00      0        0    1
2022-03-16 04:00:00      0        0    2
2022-03-16 04:00:00      0        1    1
2022-03-16 04:00:00      0        1    2

我们可以在 SUBSTRING_INDEX() 的帮助下使用 cross/inner 连接方法:

SELECT
    t1.datetime1,
    t1.count,
    t1.num1,
    t2.num2
FROM
(
    SELECT datetime1, count, SUBSTRING_INDEX(num1, ',', 1) AS num1
    FROM yourTable
    UNION ALL
    SELECT datetime1, count, SUBSTRING_INDEX(num1, ',', -1)
    FROM yourTable
) t1
INNER JOIN
(
    SELECT datetime1, count, SUBSTRING_INDEX(num2, ',', 1) AS num2
    FROM yourTable
    UNION ALL
    SELECT datetime1, count, SUBSTRING_INDEX(num2, ',', -1)
    FROM yourTable
) t2
    ON t2.datetime1 = t1.datetime1
ORDER BY
    t1.datetime1,
    t1.num1,
    t2.num2;

Demo

自版本 8+ MySql 支持 LATERAL

select t.datetime1, t.count, n1.num1, n2.num2
from tbl t
cross join lateral (
   select SUBSTRING_INDEX(t.num1, ',', 1) AS num1
    UNION ALL
   select SUBSTRING_INDEX(t.num1, ',', -1)
   ) n1
cross join lateral (
   select SUBSTRING_INDEX(t.num2, ',', 1) AS num2
    UNION ALL
   select SUBSTRING_INDEX(t.num2, ',', -1)
   ) n2

db<>fiddle