gpt4 book ai didi

mysql - 是否有将多对多链接表连接到单个记录的查询?

转载 作者:行者123 更新时间:2023-11-29 01:22:40 25 4
gpt4 key购买 nike

我在两个表之间有一个标准的多对多关系,使用第三个链接表进行链接。有没有办法通过查询将链接的 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 |
+-------------+-------------+

最佳答案

是的。使用 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 Fiddle Demo

这会给你:

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

请注意:如果您需要包含那些没有类型的事件,请改用 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

这会给你类似的东西:

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

关于mysql - 是否有将多对多链接表连接到单个记录的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14133002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com