目前我正在试验http://buysql.com/mysql/14-how-to-automate-pivot-tables.html 我需要基本的想法来运行下面的动态sql。
表:
+----+---------+---------------+--------+
| id | item_id | property_name | value |
+----+---------+---------------+--------+
| 1 | 1 | color | blue |
| 2 | 1 | size | large |
| 3 | 1 | weight | 65 |
| 4 | 2 | color | orange |
| 5 | 2 | weight | 57 |
| 6 | 2 | size | large |
| 7 | 3 | size | small |
| 8 | 3 | color | red |
| 9 | 3 | weight | 12 |
| 10 | 4 | color | violet |
| 11 | 4 | size | medium |
| 12 | 4 | weight | 34 |
| 13 | 5 | color | green |
| 14 | 5 | weight | 10 |
+----+---------+---------------+--------+
查询
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(property_name = ''',
property_name,
''', value, NULL)) AS ',
property_name
)
) INTO @sql
FROM properties;
SET @sql = CONCAT('SELECT item_id, ', @sql, ' FROM properties GROUP BY item_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
问题:如何从控制器(任何framwork或pdo)运行此语句并获取已获取的resutls ..
修改 实际上,我正在研究产品数据库。期待来自frontEnd的feature_id。参数数量未知。所以,我正在考虑根据参数创建动态查询。