简体   繁体   中英

MYSQL JOIN two tables based on a relation in third table and concat the data from the second table

here's the situation, I have tables as follows:

App table

+--------+------------+--+
| AppID  |   AppName  |  |
+--------+------------+--+
|  1     | App1       |  |
|  2     | App2       |  |
|  3     | App3       |  |
+--------+------------+--+

Tags Table

+--------+------------+--+
| TagID  |   TagName  |  |
+--------+------------+--+
|  10    | Tag1       |  |
|  20    | Tag2       |  |
|  33    | Tag3       |  |
+--------+------------+--+

AppTags Table

+--------+----------+--+
| AppID  |   TagID  |  |
+--------+----------+--+
|  1     | 20       |  |
|  1     | 30       |  |
|  2     | 10       |  |
|  2     | 30       |  |
|  3     | 10       |  |
|  3     | 20       |  |
+--------+----------+--+

I'm looking for a result like this:

+----------+---------------+--+
| AppName  |   Tags        |  |
+----------+---------------+--+
|  App1    | Tag2, Tag3    |  |
|  App2    | Tag1, Tag3    |  |
|  App3    | Tag1, Tag2    |  |
+----------+---------------+--+

I tried to use GROUP_CONCAT but I didn't know how to make a full query with a WHERE clause in it so I can define which data I want. I also of course tried to use JOIN but I was getting each TagName in a separate row with it's AppName.

Thank you.

SELECT AppName, GROUP_CONCAT(TagName) Tags
FROM AppTags  
NATURAL JOIN App
NATURAL JOIN Tags 
GROUP BY AppName;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM