简体   繁体   中英

Is there a query to join a many-to-many linked table into a single record?

I have a standard many to many relationship between two tables, linked using a third linking table. Is there anyway to JOIN the linked ids into one record with a query?

I realize I can process a typical join and build a new list with this, just wondering if it can be done with a query. Example:

EventID | EventName | EventTypeIDs

1 | Party | 1,2,3

Events
+-------------+-------------+
| Field       | Type        |
+-------------+-------------+
| EventID     | INT         |
| EventName   | varchar(45) |
+-------------+-------------+

EventTypes
+-------------+-------------+
| Field       | Type        |
+-------------+-------------+
| id          | INT         |
| value       | varchar(25) |
+-------------+-------------+

EventTypeLink
+-------------+-------------+
| Field       | Type        |
+-------------+-------------+
| id          | INT         |
| EventID     | INT         |
| EventTypeID | INT         |
+-------------+-------------+

Yes there is. Use the GROUP_CONCAT() like so:

SELECT
  e.EventId,
  e.EventName,
  GROUP_CONCAT(t.Id SEPARATOR ',') AS EventTypeIDs
FROM Events e
INNER JOIN EventTypeLink l ON e.EventId = l.EventId
INNER JOIN EventTypes    t ON l.EventTypeId = t.Id
GROUP BY   e.EventId,  
           e.EventName;

SQL Fiddle Demo

This will give you:

| EVENTID | EVENTNAME | EVENTTYPEIDS |
--------------------------------------
|       1 |     Party |        1,2,3 |

Note that: If you need to inclue those events with no types, use a LEFT JOIN instead, with IFNULL like so:

SELECT
  e.EventId,
  e.EventName,
  GROUP_CONCAT(IFNULL(t.Id,0) SEPARATOR ',') AS EventTypeIDs
FROM Events e
LEFT JOIN EventTypeLink l ON e.EventId = l.EventId
LEFT JOIN EventTypes    t ON l.EventTypeId = t.Id
GROUP BY   e.EventId,  
           e.EventName;

SQL Fiddle Demo for those with no types

This will give you something like:

| EVENTID |        EVENTNAME | EVENTTYPEIDS |
---------------------------------------------
|       1 |            Party |        3,2,1 |
|       2 | EventWithNoTypes |            0 |

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