Reputation: 11
I have some tables that look like this:
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)
);
How do I make a SELECT query that can output the title of the game in one column and all it's tags separated by comma in another. Example:
Title | Tags |
-----------------------------------
Fortnite | survival, action |
Super Mario | platform, adventure |
Upvotes: 1
Views: 1438
Reputation: 4939
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;
For insight see:
MySQL Join Made Easy For Beginners
Upvotes: 2