纵表转横表查询实现
By:授客 QQ:1033553122 欢迎加入全国软件测试交流群:7156436
实践环境
MySQL 5.7
创建测试表
CREATE TABLE tb_test (
id INT AUTO_INCREMENT PRIMARY KEY,
attr VARCHAR (20),
attr_value VARCHAR (20)
) ;
插入测试数据
INSERT INTO tb_test(attr, attr_value) VALUES(\’age\’, 18), (\’sex\’, \’男\’), (\’name\’, \’授客\’),(\’hobby\’, \’unknow\’);
查询显示:
查询需求
纵表转横表:假设attr列的值不重复,且数量有限,要求每行记录的attr值显示为查询结果中的一列(暂且称之为“属性列”),对应行记录的atrr_value值为该属性列的值
查询实现
SELECT tb_test.id,
MAX(IF(tb_test.attr = \’age\’, tb_test.attr_value, NULL)) AS age,
MAX(IF(tb_test.attr = \’sex\’, tb_test.attr_value, NULL)) AS sex,
MAX(IF(tb_test.attr = \’name\’, tb_test.attr_value, NULL)) AS `name`,
MAX(IF(tb_test.attr = \’hobby\’, tb_test.attr_value, NULL)) AS hobby
FROM tb_test;
查询结果