問題描述
此時我可能看的不是很清楚,但我在 MySQL 中有一個表,如下所示:
I'm probably not seeing things very clear at this moment, but I have a table in MySQL which looks like this:
ID | a | b | c
1 | a1 | b1 | c1
2 | a2 | b2 | c2
出于某種原因(實際上是另一個表上的連接 - 基于 ID
,但我認為如果有人可以幫助我完成這部分,我可以自己完成其余部分),我需要這些行改為這樣:
For some reason (actually a join on another table - based on ID
, but I think if someone can help me out with this part, I can do the rest myself), I needed those rows to be like this instead:
1 | a1 | a
1 | b1 | b
1 | c1 | c
2 | a2 | a
2 | b2 | b
2 | c2 | c
所以基本上,我需要查看如下行:ID
、columntitle
、value
有什么方法可以輕松做到這一點嗎?
So basically, I need to view the rows like: ID
, columntitle
, value
Is there any way to do this easily?
推薦答案
您正在嘗試反透視數據.MySQL 沒有 unpivot 功能,因此您必須使用 UNION ALL
查詢將列轉換為行:
You are trying to unpivot the data. MySQL does not have an unpivot function, so you will have to use a UNION ALL
query to convert the columns into rows:
select id, 'a' col, a value
from yourtable
union all
select id, 'b' col, b value
from yourtable
union all
select id, 'c' col, c value
from yourtable
參見SQL Fiddle with Demo.
這也可以使用 CROSS JOIN
來完成:
This can also be done using a CROSS JOIN
:
select t.id,
c.col,
case c.col
when 'a' then a
when 'b' then b
when 'c' then c
end as data
from yourtable t
cross join
(
select 'a' as col
union all select 'b'
union all select 'c'
) c
參見SQL Fiddle with Demo
這篇關于MySQL - 如何將列反透視為行?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!