MySQL - 基于列的值加入?

时间:2017-03-22 14:46:55

标签: mysql join subquery

我有两张桌子:

Table "categories"

category  |  parents
1         |  5,4,1
2         |  3,2

列父项是用逗号分隔的数字组,因此可以在查询中用作IN(parents)

Table "categories_goods"

item | category
10   | 1
12   | 2

我想将数据导出到第三个表格 - 每个类别都会有所有父母。结果应该是:

Table "categories_goods_all"

item | category
10   | 5
10   | 4
10   | 1
12   | 3
12   | 2

我在PHP中解决了这个问题,但是当表category_goods中存在10000 * x行时,它很慢。所以我在寻找纯MySQL解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用此

演示: http://rextester.com/CAF76544

查询

select
  g.item,
  SUBSTRING_INDEX(SUBSTRING_INDEX(c.parents, ',', numbers.n), ',', -1) category1
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers 
 INNER JOIN categories c 
  on CHAR_LENGTH(c.parents)
     -CHAR_LENGTH(REPLACE(c.parents, ',', ''))>=numbers.n-1
  inner join categories_goods g
  on c.category=g.category 
order by
  c.category, n

感谢此answer将csv拆分为行。

说明:number表生成号码1 - 5。如果需要更多parent,您可能需要在此处添加更多行。在其帮助下,您可以将csv分隔为列。请参阅上面给出的答案网址。

现在您只需要加入categories_goods即可获取与item对应的parent