如何从一行中的字段创建单独的行?
How to create a separate row from the fields in one row?
我有一个 table 这样的:
// mytable
+----+--------+--------+
| id | col1 | col2 |
+----+--------+--------+
| 1 | one | two |
| 2 | three | four |
| 3 | five | six |
+----+--------+--------+
现在我想要这个 table:
// newmytable
+----+-------+---------+
| id | col | related |
+----+-------+---------+
| 1 | one | 1 |
| 2 | two | 1 |
| 3 | three | 2 |
| 4 | four | 2 |
| 5 | five | 3 |
| 6 | six | 3 |
+----+-------+---------+
我可以在没有 related
列的情况下这样做:
CREATE TABLE newmytable (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
SELECT col1 AS col FROM mytable
UNION ALL
SELECT col2 AS col FROM mytable
)
但现在我想知道,如何才能包含 related
列?
您可以使用 id
填充 related
列,如下所示:
CREATE TABLE newmytable (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY)
SELECT col, related FROM (
SELECT col1 AS col, id as related, 0 sort FROM mytable
UNION ALL
SELECT col2 AS col, id as related, 1 sort FROM mytable
) x
ORDER BY x.related,x.sort ASC
Demo
我有一个 table 这样的:
// mytable
+----+--------+--------+
| id | col1 | col2 |
+----+--------+--------+
| 1 | one | two |
| 2 | three | four |
| 3 | five | six |
+----+--------+--------+
现在我想要这个 table:
// newmytable
+----+-------+---------+
| id | col | related |
+----+-------+---------+
| 1 | one | 1 |
| 2 | two | 1 |
| 3 | three | 2 |
| 4 | four | 2 |
| 5 | five | 3 |
| 6 | six | 3 |
+----+-------+---------+
我可以在没有 related
列的情况下这样做:
CREATE TABLE newmytable (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
SELECT col1 AS col FROM mytable
UNION ALL
SELECT col2 AS col FROM mytable
)
但现在我想知道,如何才能包含 related
列?
您可以使用 id
填充 related
列,如下所示:
CREATE TABLE newmytable (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY)
SELECT col, related FROM (
SELECT col1 AS col, id as related, 0 sort FROM mytable
UNION ALL
SELECT col2 AS col, id as related, 1 sort FROM mytable
) x
ORDER BY x.related,x.sort ASC