MySQL - 将表转换为不同的表

时间:2022-05-03 00:47:07

I'm probably not seeing things very clear at this moment, but I have a table in MySQL which looks like this:

我现在可能没有看到很清楚的事情,但我在MySQL中有一个表,如下所示:

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

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:

出于某种原因(实际上是在另一个表上加入 - 基于ID,但我想如果有人可以帮我解决这个问题,我可以自己做其余的事情),我需要这些行代替:

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

So basically, I need to view the rows like: ID, columntitle, value Is there any way to do this easily?

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

2 个解决方案

#1


18  

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:

您正试图取消数据。 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

See SQL Fiddle with Demo.

请参阅SQL Fiddle with Demo。

This can also be done using a CROSS JOIN:

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

See SQL Fiddle with Demo

请参阅SQL Fiddle with Demo

#2


3  

Try to use UNION ALL.

尝试使用UNION ALL。

SELECT ID, a, 'a' 
FROM tbl
WHERE ID = 1
UNION
SELECT ID, b, 'b' 
FROM tbl
WHERE ID = 2

#1


18  

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:

您正试图取消数据。 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

See SQL Fiddle with Demo.

请参阅SQL Fiddle with Demo。

This can also be done using a CROSS JOIN:

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

See SQL Fiddle with Demo

请参阅SQL Fiddle with Demo

#2


3  

Try to use UNION ALL.

尝试使用UNION ALL。

SELECT ID, a, 'a' 
FROM tbl
WHERE ID = 1
UNION
SELECT ID, b, 'b' 
FROM tbl
WHERE ID = 2