如何连接结点表中的笛卡尔积加入MySQL

前端之家收集整理的这篇文章主要介绍了如何连接结点表中的笛卡尔积加入MySQL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有三个表:项目,交汇点和属性.我有五个项目(A到E)和五个属性(1到5).通过Junction Table,我已经分配了如下属性

  1. A: 1,3,5
  2. B: 1,2,3
  3. C: 1,4,5
  4. D: 1,3
  5. E: 1,5

当我运行以下查询时,我得到了一个可爱的十五记录笛卡尔积(正如人们所期望的那样).

  1. SELECT I.id,I.item_name,P.property_name FROM scratch.items I
  2. JOIN scratch.junction J ON J.item_id = I.id
  3. JOIN scratch.property P ON J.property_id = P.id;

我想要做的是将每个项目的属性名称连接到一个字段中,这样我就可以像这样吐出它们:

  1. Record | item_id | item_name | properties
  2. ----------------------------------------------------------------------------
  3. 0 | A | Item A | Property 1,Property 3,Property 5
  4. 1 | B | Item B | Property 1,Property 2,Property 3
  5. 2 | C | Item C | Property 1,Property 4,Property 5
  6. 3 | D | Item D | Property 1,Property 3
  7. 4 | E | Item E | Property 1,Property 5
  8. ----------------------------------------------------------------------------

与我此处的设计示例不同,每个项目可以包含任意数量属性(包括零).

最佳答案
您可以像这样使用group_concat函数

  1. SELECT I.id,group_concat(P.property_name) as properties
  2. FROM scratch.items I
  3. JOIN scratch.junction J ON J.item_id = I.id
  4. JOIN scratch.property P ON J.property_id = P.id
  5. group by I.id;

猜你在找的MySQL相关文章