我正在尝试遵循此站点中的示例: http://vitobotta.com/mysql-generate-column-names-dynamically-from-row-values/
我有一张这样的 table :
+------------+--------------+----------+-------------+
| MessageId | ProcessDate | FieldName | FieldValue |
+------------+--------------+-----------+------------+
| 18 | 2015-12-04 | data | 101110101 |
| 18 | 2015-12-04 | type | binary |
| 19 | 2015-12-04 | type | integer |
| 19 | 2015-12-04 | data | 34 |
+------------+--------------+-----------+------------+
我想要的是这样的:
+------------+--------------+----------+-------------+
| MessageId | ProcessDate | type | data |
+------------+--------------+-----------+------------+
| 18 | 2015-12-04 | binar | 101110101 |
| 19 | 2015-12-04 | integer | 34 |
+------------+--------------+-----------+------------+
我的代码:
DROP TABLE IF EXISTS tmp_results;
CREATE TEMPORARY TABLE tmp_results AS
SELECT r.`MessageId`, r.`ProcessDate`, r.`TransportType`, d.`FieldName`, d.`FieldValue`
FROM
returnmessages r, decodedmessagessummaryrecord s, decodedmessagesdetailrecord d
WHERE r.`Id` = s.`ReturnMessagesId`
AND s.`Id` = d.`DecodedMessagesSummaryRecordId`
AND r.`MobileId` = "35"
LIMIT 10;
SELECT CONCAT('
SELECT MessageId, ProcessDate, TransportType, ', field_value, '
FROM tmp_results'
)
INTO @variable1
FROM
(SELECT GROUP_CONCAT(CONCAT('IFNULL(MAX(CASE WHEN FieldName=''',field_name,''' THEN FieldValue
END), ''-'' AS "', col_name,'"')) field_value
FROM(
SELECT field_name, field_name as col_name
FROM(SELECT DISTINCT FieldName AS field_name FROM tmp_results) AS fieldnames
) field_with_col_names
) result;
PREPARE prepstate FROM @s;
EXECUTE prepstate;
DEALLOCATE PREPARE prepstate;
这会返回一个错误:
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tmp_results' at line 3
我现在不太确定出了什么问题。
最佳答案
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when FieldName = ''',
FieldName,
''' then FieldValue end) AS ',
'`',FieldName,'`'
)
) INTO @sql
from tmp_results;
SET @sql = CONCAT('SELECT MessageId, ProcessDate, TransportType, ', @sql, ' from tmp_results
group by MessageId');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
关于将行值转换为列的 MySql 准备语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37012546/