如何从一行中的字段创建单独的行?

时间:2016-01-08 15:48:58

标签: mysql union-all

我有一张这样的表:

// 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列?

1 个答案:

答案 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

Demo