我有一张这样的表:
// mytable
+----+--------+--------+
| id | col1 | col2 |
+----+--------+--------+
| 1 | one | two |
| 2 | three | four |
| 3 | five | six |
+----+--------+--------+
现在我想要这张桌子:
// 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
列?
答案 0 :(得分:1)
您可以使用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