MySql准备语句将行值转换为列

时间:2016-05-03 19:14:01

标签: mysql prepared-statement

我试图关注此网站的示例: http://vitobotta.com/mysql-generate-column-names-dynamically-from-row-values/

我有一张像这样的表:

+------------+--------------+----------+-------------+
| 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;

返回错误:

  

错误代码:1064。您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在' FROM tmp_results'附近使用正确的语法。在第3行

我现在还不确定到底出了什么问题。

1 个答案:

答案 0 :(得分:0)

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;

FIDDLE