使用MySQL将表列转换为表行

时间:2014-05-26 06:00:24

标签: mysql sql

您好,

知道如何将列转换为行吗?

表格如下:

+----+--------+---------+-----------+---------+
| id |  name  | morning | afternoon | evening |
+----+--------+---------+-----------+---------+
|  1 | apple  |       1 |         2 |       1 |
|  2 | banana |       2 |         2 |       1 |
|  3 | orange |       1 |         2 |       3 |
+----+--------+---------+-----------+---------+

结果应如下所示:

+----+--------+-----------+-----+
| id |  name  |    day    | no. |
+----+--------+-----------+-----+
|  1 | apple  | morning   |   1 |
|  1 | apple  | afternoon |   2 |
|  1 | apple  | evening   |   1 |
|  2 | banana | morning   |   2 |
|  2 | banana | afternoon |   2 |
|  2 | banana | evening   |   1 |
|  3 | orange | morning   |   1 |
|  3 | orange | afternoon |   2 |
|  3 | orange | evening   |   3 |
+----+--------+-----------+-----+

2 个答案:

答案 0 :(得分:0)

试试这个,

SELECT id,NAME,morning AS NO ,'morning'  AS DAY FROM tablename
UNION ALL
SELECT id,NAME,afternoon NO,'afternoon' AS DAY FROM tablename
UNION ALL
SELECT id,NAME,evening AS NO , 'evening' AS DAY FROM tablename
ORDER BY id

答案 1 :(得分:0)

使用union all可以完成选择,但是您希望使用订单名称显示数据,这样您就可以使用外部select语句和子查询来使用union选择数据所有内容

select
id,name,day,no
from
(
select id , name , 'morning' as day,morning as no from test
union all
select id , name , 'afternoon' as day,afternoon as no from test
union all
select id , name , 'evening' as day,evening as no from test
)x
order by name

<强> DEMO