使用一个表中的结果字符串作为另一个查询的列名

时间:2016-07-11 12:40:00

标签: mysql

我正在尝试简化以下查询: -

SELECT id, m_field_id_46 AS Liverpool,m_field_id_47 AS London,m_field_id_48 AS Belfast FROM member_data

在某种程度上,我可以动态创建列名

SELECT id, (SELECT GROUP_CONCAT('m_field_id_',m_field_id,' AS ',m_field_label) FROM member_fields) as dist FROM member_data

然而这不起作用。请帮忙

1 个答案:

答案 0 :(得分:0)

我通过查看stackoverflow的另一个答案让它工作: -

SET @listStr = ( SELECT GROUP_CONCAT('md.m_field_id_',m_field_id,' AS `',m_field_label,'`') FROM member_fields );
SET @query := CONCAT('SELECT ', @listStr, ' FROM member_data');
PREPARE STMT FROM @query;
EXECUTE STMT;