如何在MySQL中将递归自连接列表连接成一个字符串?

时间:2018-01-06 20:02:42

标签: mysql

我有4张桌子:

products
- id
- name

categories
- id
- name

category_products
- product_id
- category_id

category_relationships
- parent_category_id
- child_category_id

每个产品都有一个类别。每个类别通过category_relationships表都有[n]个父类别。

我怎样才能编写一个结果如下的查询:

| product.id | product.name | category_list                      |
*------------*--------------*------------------------------------*
| 1          | test product | cat1, parent1, gparent1, gparent 2 | 

我确信这是自我联盟,工会等的一些组合,但我似乎无法得到正确的组合。

更新: 我不打算用sql解决这个问题,而只是用一个命中MySQL的脚本解决它。

1 个答案:

答案 0 :(得分:0)

实际上我想出了一个查询来做到这一点。我已经知道我的递归并没有超过3或4,所以我在6个级别安全地进行了游戏,按父类别的连接分组(因为一些产品也开始有多个类别)。这将生成一个与我的产品数量完全相同的结果集,并以空格分隔的字符串(用作标记)吐出父类别列表。

SELECT
    products.id,
    products.name,
    category_products.category_id,
    GROUP_CONCAT( 
      CONCAT_WS(' ', 
      (select name from categories where id = c1.parent),
      (select name from categories where id = c2.parent),
      (select name from categories where id = c3.parent),
      (select name from categories where id = c4.parent),
      (select name from categories where id = c5.parent),
      (select name from categories where id = c6.parent)
    ) SEPARATOR ' ') as parents,
    (select name from categories where id = c1.parent) as c1parent,
    (select name from categories where id = c2.parent) as c2parent,
    (select name from categories where id = c3.parent) as c3parent,
    (select name from categories where id = c4.parent) as c4parent,
    (select name from categories where id = c5.parent) as c5parent,
    (select name from categories where id = c6.parent) as c6parent
  from products 
  LEFT JOIN category_products
    LEFT JOIN category_relationships as c1 on category_products.category_id = c1.child
    LEFT JOIN category_relationships as c2 on c2.child = c1.parent
    LEFT JOIN category_relationships as c3 on c3.child = c2.parent
    LEFT JOIN category_relationships as c4 on c4.child = c3.parent
    LEFT JOIN category_relationships as c5 on c5.child = c4.parent
    LEFT JOIN category_relationships as c6 on c6.child = c5.parent
  on product_id = products.id
  GROUP BY id;