mysql临时表自连接,如何在MySQL中进行递归自联接

I'm building a webshop which needs to produce a gatherlist.

The problem is that i have 3 kinds of products and a recursive table (infinite).

namely Products, Option and Category, were category's are the recursive ones.

I'm trying to build a view with the fields Order.id, OrderProduct.product, Component.id.

Here you can see what i've already, however i removed the part of -- by option as it doesn't 'feed' the example.

CREATE VIEW `Gatherlist` as

SELECT `O`.`id`, `OP`.`product`, `C`.`id` FROM `Order` `O` -- By Product

LEFT JOIN `OrderProduct` `OP`

ON `O`.`id` = `OP`.`order`

LEFT JOIN `Product` `P`

ON `OP`.`product` = `P`.`id`

LEFT JOIN `ProductComponent` `PC`

ON `P`.`id` = `PC`.`product`

LEFT JOIN `Component` `C`

ON `PC`.`component` = `C`.`id`

UNION ALL

SELECT `O`.`id`, `OP`.`product`, `C`.`id` FROM `Order` `O` -- By Category

LEFT JOIN `OrderProduct` `OP`

ON `O`.`id` = `OP`.`order`

LEFT JOIN `Product` `P`

ON `OP`.`product` = `P`.`id`

-- LEFT JOIN `Category` `PC`

-- ON `P`.`category` = `PC`.`id`

-- Here should start a recursive join on Category

INNER JOIN (

SELECT group_concat(@id :=

(

SELECT id

FROM `Category`

WHERE parent = @id

)

) AS categoryTemp

FROM (

SELECT @id := 1

) vars

STRAIGHT_JOIN

`Category`

WHERE @id IS NOT NULL

) as `PC` on `P`.`category` = `PC`.`id`

-- And it will end somewhere again (i hope)

LEFT JOIN `CategoryCompenent` `CC`

ON `PC`.`id` = `CC`.`category`

LEFT JOIN `Component` `C`

ON `CC`.`component` = `C`.`id`

ORDER BY `O`.`id`, `OP`.`product`, `C`.`id`

My table Category looks like this:

id - Obvious

label - id of a name in another table

parent - the id of the above laying Category

I have found this but could not figure out how to put it in a join (within a view with unions).

SELECT group_concat(@id :=

(

SELECT id

FROM comments

WHERE parent_id = @id

)) AS comment

FROM (

SELECT @id := 1

) vars

STRAIGHT_JOIN

comments

WHERE @id IS NOT NULL

解决方案

There is no real way (at least that I know of) to do a "recursive" join in MySQL. If you have such a table structure, the best solution I know of is using stored procedures to loop through and "collect" related rows and/or build "paths"; unfortunately, you cannot join to the results of a stored procedure, so that usually means having it drop that data into a predetermined temp table to be used after the procedure has executed.

Alternately, you can analyse the recursive table in code to determine its current "depth" in order to compose the query programmatically.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值