これは、CASE
を使用して行うことができます ステートメント:
SELECT p.productid, p.da, p.ig, p.des
,GROUP_CONCAT(CASE WHEN ck.title = 'St Code'
THEN cv.value ELSE NULL END) AS 'St Code'
,GROUP_CONCAT(CASE WHEN ck.title = 'Rear Les'
THEN cv.value ELSE NULL END) AS 'Rear Les'
FROM Products p
JOIN code_values cv ON p.productid = cv.pid
JOIN code_keys ck ON cv.codeid = ck.codeid
GROUP BY p.productid;
code_keys
の数が不明な場合 この動的クエリを試すことができます:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'GROUP_CONCAT(CASE WHEN `title` = ''',
`title`,
''' THEN cv.value ELSE NULL END) AS `',
`title`, '`'
)
) INTO @sql
FROM code_keys ck JOIN code_values cv ON cv.codeid = ck.codeid;
SET @sql = CONCAT('SELECT p.productid, p.da, p.ig, p.des, ', @sql,'
FROM Products p
JOIN code_values cv ON p.productid = cv.pid
JOIN code_keys ck ON cv.codeid = ck.codeid
GROUP BY p.productid
');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
出力:
| PRODUCTID | DA | IG | DES | ST CODE | REAR LES |
--------------------------------------------------------
| 5 | 78 | 33 | 23 | ST 102 200 R | 12 000 33 |
| 8 | 88 | 13 | 21 | ST 100 101 R | 11 223 34 |