Du kan göra detta med CASE
uttalande:
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;
Om du har okänt antal code_keys
du kan prova den här dynamiska frågan:
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;
Utdata:
| 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 |