我有一些看起来像这样的表:
CREATE TABLE Games (
Id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
Title VARCHAR(100) NOT NULL
);
CREATE TABLE Tags(
Id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
Tag VARCHAR(30) NOT NULL
);
CREATE TABLE GamesTags(
GameId INTEGER NOT NULL,
TagId INTEGER NOT NULL,
PRIMARY KEY (GameId, TagId),
FOREIGN KEY(GameId) REFERENCES Games(Id),
FOREIGN KEY(TagId) REFERENCES Tags(Id)
);
如何创建一个SELECT查询,该查询可以在一列中输出游戏的标题,而在另一列中用逗号分隔所有标记。例如:
Title | Tags |
-----------------------------------
Fortnite | survival, action |
Super Mario | platform, adventure |
答案 0 :(得分:1)
SELECT
A.Title,
GROUP_CONCAT(DISTINCT C.Tag ORDER BY C.Tag ASC SEPARATOR ',') Tags
FROM Games A
LEFT JOIN GameTags B
ON A.Id=B.GameID
LEFT JOIN Tags C
ON B.TagId=C.Id
GROUP BY A.Title;
有关见解,请参阅: