我有这些表的MySQL数据库:
表产品:
+-------------+
| id |
+-------------+
| 1 |
| 2 |
+-------------+
table attribute_values:
+-------------+----------+-----------+
| product_id | key | value |
+-------------+----------+-----------+
| 1 | title | Orange |
| 1 | code | O125 |
| 2 | title | Pizza |
| 2 | code | O138 |
+-------------+----------+-----------+
我有这个MySQL查询:
SELECT products.id,
MAX(CASE WHEN attribute_values.key = 'title' THEN attribute_values.value END) title,
MAX(CASE WHEN attribute_values.key = 'code' THEN attribute_values.value END) code
FROM products JOIN attribute_values ON products.id = attribute_values.product_id
GROUP BY products.id;
使用此输出:
+-------------+----------+-----------+
| id | title | code |
+-------------+----------+-----------+
| 1 | Orange | 0125 |
| 2 | Pizza | O138 |
+-------------+----------+-----------+
我希望脚本为attribute_values.key的每个不同值生成一列,而不显式指定键(在这种情况下为标题和代码)。
即。 pseudoscript:
SELECT products.id
generate column foreach distinct attribute_values.key
FROM products JOIN attribute_values ON products.id = attribute_values.product_id
GROUP BY products.id;
这在MySQL中是否可行?
感谢您的任何努力:)
答案 0 :(得分:2)
要为动态值生成动态数据透视表,您需要将动态sql编写为
set @sql = null;
select
group_concat(distinct
concat(
'max(case when a.`key` = ''',
a.`key`,
''' then value end) AS ',
a.`key`
)
) into @sql
from attribute_values a ;
set @sql = concat('select p.id, ', @sql, ' from products p
join attribute_values a on a.product_id = p.id
group by p.id
');
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;