MySQL - 如何将列转为行?

MySQL - How to unpivot columns to rows?(MySQL - 如何将列转为行?)
本文介绍了MySQL - 如何将列转为行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此时我可能还不太清楚,但我在 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

所以基本上,我需要查看如下行:IDcolumntitlevalue有什么方法可以轻松做到这一点?

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

推荐答案

您正在尝试unpivot数据.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 - 如何将列转为行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)