2

我在两个表之间有一个标准的多对多关系,使用第三个链接表链接。有没有办法通过查询将链接的 ID 加入一条记录?

我意识到我可以处理一个典型的连接并用它构建一个新列表,只是想知道它是否可以通过查询来完成。例子:

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         |
+-------------+-------------+
4

1 回答 1

6

就在这里。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;

SQL 小提琴演示

这会给你:

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

请注意:如果您需要包含那些没有类型的事件,请改用 a LEFT JOINIFNULL如下所示:

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 演示

这会给你类似的东西:

| EVENTID |        EVENTNAME | EVENTTYPEIDS |
---------------------------------------------
|       1 |            Party |        3,2,1 |
|       2 | EventWithNoTypes |            0 |
于 2013-01-03T04:23:34.407 回答