MySQL行轉列的實現方式有以下幾種:
SELECT
id,
MAX(CASE WHEN attribute = 'attribute1' THEN value END) AS attribute1,
MAX(CASE WHEN attribute = 'attribute2' THEN value END) AS attribute2,
MAX(CASE WHEN attribute = 'attribute3' THEN value END) AS attribute3
FROM
table
GROUP BY
id;
SELECT
id,
MAX(CASE WHEN attribute = 'attribute1' THEN value END) AS attribute1,
MAX(CASE WHEN attribute = 'attribute2' THEN value END) AS attribute2,
MAX(CASE WHEN attribute = 'attribute3' THEN value END) AS attribute3
FROM
(SELECT id, attribute, value FROM table) AS t
GROUP BY
id;
SELECT
id,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN attribute = 'attribute1' THEN value END), ',', 1) AS attribute1,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN attribute = 'attribute2' THEN value END), ',', 1) AS attribute2,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN attribute = 'attribute3' THEN value END), ',', 1) AS attribute3
FROM
table
GROUP BY
id;
以上是幾種常見的MySQL行轉列的實現方式,可以根據實際需求選擇適合的方式。