MySQL - 如何将列转换为行?
P粉533898694
P粉533898694 2023-07-24 23:17:01
0
1
447
<p><br /></p> <pre class="brush:php;toolbar:false;">ID | a | b | c 1 | a1 | b1 | c1 2 | a2 | b2 | c2</pre> <p>如何将行重新组织为ID,列标题,值?</p> <pre class="brush:php;toolbar:false;">1 | a1 | a 1 | b1 | b 1 | c1 | c 2 | a2 | a 2 | b2 | b 2 | c2 | c</pre> <p><br /></p>
P粉533898694
P粉533898694

全部回复(1)
P粉511896716

您正在尝试对数据进行反转。MySQL没有反转函数,因此您需要使用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.

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

热门教程
더>
最新下载
더>
网站特效
网站源码
网站素材
프론트엔드 템플릿
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!