我有三个表:items,junction,和properties.我有五个项目(A到E)和五个属性(1到5).通过Junction Table,我已经分配了如下属性:
A: 1, 3, 5
B: 1, 2, 3
C: 1, 4, 5
D: 1, 2, 3
E: 1, 4, 5
Run Code Online (Sandbox Code Playgroud)
当我运行以下查询时,我得到了一个可爱的十五记录笛卡尔积(正如人们所期望的那样).
SELECT I.id, I.item_name, P.property_name FROM scratch.items I
JOIN scratch.junction J ON J.item_id = I.id
JOIN scratch.property P ON J.property_id = P.id;
Run Code Online (Sandbox Code Playgroud)
我想要做的是将每个项目的属性名称连接到一个字段中,这样我就可以像这样吐出它们:
Record | item_id | item_name | properties
----------------------------------------------------------------------------
0 | A | Item A | Property 1, Property 3, Property 5
1 | B | Item B | Property 1, Property 2, Property 3
2 | C | Item C | Property 1, Property 4, Property 5
3 | D | Item D | Property 1, Property 2, Property 3
4 | E | Item E | Property 1, Property 4, Property 5
----------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
与我此处的设计示例不同,每个项目可以包含任意数量的属性(包括零).
小智 4
您可以像这样使用 group_concat 函数:
SELECT I.id, I.item_name, group_concat(P.property_name) as properties
FROM scratch.items I
JOIN scratch.junction J ON J.item_id = I.id
JOIN scratch.property P ON J.property_id = P.id
group by I.id;
Run Code Online (Sandbox Code Playgroud)