SELECT a.id,
a.name,
SUM(CASE WHEN c.size = 'S' THEN 1 ELSE 0 END) `S`,
SUM(CASE WHEN c.size = 'M' THEN 1 ELSE 0 END) `M`,
SUM(CASE WHEN c.size = 'L' THEN 1 ELSE 0 END) `L`,
SUM(CASE WHEN c.size = 'XL' THEN 1 ELSE 0 END) `XL`,
SUM(CASE WHEN c.size = 'XXL' THEN 1 ELSE 0 END) `XXL`
FROM items a
LEFT JOIN item_sizes b
ON a.id = b.item_id
LEFT JOIN sizes c
ON b.size_ID = c.id
GROUP BY a.id, a.name
利用PreparedStatament
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN c.size = ''',
size,
''' then 1 ELSE 0 end) AS ',
size
)
) INTO @sql
FROM sizes;
SET @sql = CONCAT('SELECT a.id,
a.name, ', @sql, '
FROM items a
LEFT JOIN item_sizes b
ON a.id = b.item_id
LEFT JOIN sizes c
ON b.size_ID = c.id
GROUP BY a.id, a.name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;