21

我现在可能看不太清楚,但我在 MySQL 中有一个如下所示的表:

ID | a  | b  | c 
1  | a1 | b1 | c1
2  | a2 | b2 | c2

ID出于某种原因(实际上是在另一个表上的连接 - 基于

1 | a1 | a
1 | b1 | b
1 | c1 | c
2 | a2 | a
2 | b2 | b
2 | c2 | c

所以基本上,我需要查看如下行: ID, columntitle,value 有没有办法轻松做到这一点?

4

3 回答 3

26

您正在尝试对数据进行反透视。MySQL 没有 unpivot 函数,因此您必须使用UNION ALL查询将列转换为行:

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

这也可以使用 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

于 2013-03-04T00:12:11.353 回答
2

尝试使用UNION ALL

SELECT ID, a, 'a' 
FROM tbl
WHERE ID = 1
UNION
SELECT ID, b, 'b' 
FROM tbl
WHERE ID = 2
于 2013-03-04T00:08:23.403 回答
2

It took a long time coming, but MySQL version 8.0.14 finally added support for lateral joins - the official terminology is lateral derived tables.

This is a very powerful feature, that comes handy in multiple situations, including unpivoting table columns to rows.

You can phrase the query as follows:

select t.id, x.*
from mytable t
cross join lateral (
    select a, 'a' 
    union all select b, 'b'
    union all select c, 'c'
) as x(col1, col2)

It may look like this is not a big difference compared to the typical cannonical solution - after all, we are still using union all within the lateral derived table... But don't get it wrong: this query scans the table only once, as opposed to the other approach, which requires one scan for each column to unpivot. So this is more efficient - and the performance gain increases dramatically as the table goes bigger and/or more columns need to be unpivoted.

Bottom line: if you are running MySQL 8.0.14 or higher, just use this technique. From that version onwards, this is the canonical way to unpivot in MYSQL.

Demo on DB Fiddle:

Sample data:

ID | a  | b  | c 
-: | :- | :- | :-
 1 | a1 | b1 | c1
 2 | a2 | b2 | c2

Query results:

id | col1 | col2
-: | :--- | :---
 1 | a1   | a   
 1 | b1   | b   
 1 | c1   | c   
 2 | a2   | a   
 2 | b2   | b   
 2 | c2   | c   

Side note

MySQL 8.0.19 added support for the VALUES statement, which could help further shortening the query by removing the need to use union all in a subquery (although I don't see any performance gain here, this makes the query neater).

nfortunately, As of version 8.0.21, this does not work yet - which might be considered a bug - but maybe will in a future version...:

select t.id, x.*
from mytable t
cross join lateral (values 
    row(a, 'a'), 
    row(b, 'b'),
    row(c, 'c')
) as x(col1, col2);
于 2020-10-17T16:42:26.050 回答