[英]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? 无论如何,通过查询将链接的ID连接到一条记录中?
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: 像这样使用GROUP_CONCAT()
:
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;
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: 请注意:如果需要包含没有类型的事件,请使用带有IFNULL
的LEFT JOIN
代替, IFNULL
所示:
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 适用于无类型用户的SQL Fiddle演示
This will give you something like: 这将为您提供以下信息:
| EVENTID | EVENTNAME | EVENTTYPEIDS |
---------------------------------------------
| 1 | Party | 3,2,1 |
| 2 | EventWithNoTypes | 0 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.