【发布时间】:2021-04-03 00:08:40
【问题描述】:
我在使用来自 3 个表的连接和连接数据构建选择请求时遇到问题。
第一个表 entity 有一些实体的 ID 及其作者:
| id | author |
|---|---|
| 11 | "John" |
| 12 | "Mike" |
| 13 | "Kevin" |
第 2 和第 3 表包含与此实体相关的部分和文件,每行占一行。任何实体的节数和文件数都可以不同。
文件:
| id | entity_id | file_name |
|---|---|---|
| 1 | 11 | file1 |
| 2 | 12 | file1 |
| 3 | 12 | file2 |
| 4 | 12 | file3 |
| 5 | 13 | file4 |
| 6 | 13 | file5 |
| 7 | 13 | file6 |
section(在这个例子中,有些实体也可以是没有部分的,比如 12):
| id | entity_id | section_id |
|---|---|---|
| 1 | 11 | 1001 |
| 2 | 11 | 1002 |
| 3 | 13 | 1003 |
我需要从连接相关部分和文件的实体表中选择所有数据作为逗号分隔的字符串。为此,我创建了以下请求:
SELECT
entity.id,
entity.author,
group_concat(section.section_id) section_ids,
group_concat(file.file_name) files
FROM entity
LEFT JOIN file ON entity.id = file.entity_id
LEFT JOIN section ON entity.id = section.entity_id
group by entity.id;
我希望得到以下结果:
| id | author | files | section_ids |
|---|---|---|---|
| 11 | "John" | file1 | 1001,1002 |
| 12 | "Mike" | file1,file2,file3 | null |
| 13 | "Kevin" | file4,file5,file6 | 1003 |
但实际上我得到了这个:
| id | author | files | section_ids |
|---|---|---|---|
| 11 | "John" | file1,file1 | 1001,1002 |
| 12 | "Mike" | file1,file2,file3 | null |
| 13 | "Kevin" | file4,file5,file6 | 1003,1003,1003 |
看起来文件在实体有多个部分时重复,而在实体有多个文件时部分重复。 我尝试使用不同类型的连接(内/外,右/左),但没有找到任何解决方案。请帮我解决这个问题。
【问题讨论】:
标签: mysql sql join select aggregate-functions