我需要创建一个列出以下表的SQL查询。语言列表中的行作为列名。感谢
图片表和查询:
答案 0 :(得分:0)
如果预先知道语言
SELECT r.id, r.parent,
MAX(CASE WHEN n.language_id = 1 THEN n.name END) cs,
MAX(CASE WHEN n.language_id = 2 THEN n.name END) en
FROM cat_route r LEFT JOIN cat_route_name n
ON r.id = n.cat_route_id
GROUP BY r.id
这是 SQLFiddle 演示
如果您希望它是动态的,具体取决于您在language
SET @sql = NULL;
SELECT GROUP_CONCAT(CONCAT(
'MAX(CASE WHEN n.language_id = ', id, ' THEN n.name END) `', short, '`'))
INTO @sql
FROM language;
SET @sql = CONCAT(
'SELECT r.id, r.parent, ', @sql, '
FROM cat_route r LEFT JOIN cat_route_name n
ON r.id = n.cat_route_id
GROUP BY r.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
这是 SQLFiddle 演示