mysql 列转行

728 阅读1分钟

mysql 列转行

select * from tablename

得出数据为 在这里插入图片描述

字段为attr1,attr2,attr3等,现在想把列转行,要这种结果:

在这里插入图片描述 sql语句: 可以使用information_schema.COLUMNS 来查询出表的字段名字。这样

select COLUMN_NAME  clouname,
       (
           case col.COLUMN_NAME
               when 'attr1' then zu.attr1
               when 'attr2' then zu.attr2
               when 'attr3' then zu.attr3
               when 'attr4' then zu.attr4
               when 'attr5' then zu.attr5
               when 'attr6' then zu.attr6
               end) 'value'
from information_schema.COLUMNS col,
     zujianduibitest1 zu
where col.TABLE_NAME = 'table_name'
  and zu.attr1 = '条件的值';