For the composite tree structure of data storage in mysql, the query results are output in the tree structure _ MySQL

Source: Internet
Author: User
For the composite tree structure of data storage in mysql, bitsCN.com is output according to the tree structure during query.

1. main idea: regular data creation based on existing data

Select * FROM (
Select lId, strName, lId as lParentId,-1 as orderIdx from tbClassify WHERE lParentId = 0
UNION ALL
(Select t1. * from tbClassify t1 join
(Select lId from tbClassify where lParentId = 0 order by orderIdx) t2 on
T1.lParentId = t2.lId
Where 1 = 1 order by t1.lParentId, t1.orderIdx)
) TbLast where 1 = 1 group by tbLast. lParentId, tbLast. lId order by tbLast. lParentId, tbLast. orderIdx
;

There is a problem with the sorting above, and the final shape is:

Select lId FROM (
Select lId, orderIdx as pIdx,-1 as sIdx from tbClassify WHERE lParentId = 0
UNION ALL
(Select a. lId, B. orderIdx pIdx, a. orderIdx sIdx from tbClassify a left JOIN tbClassify B on (a. lParentId = B. lId) where a. lParentId! = 0)
)
TbLast order by tbLast. pIdx, tbLast. sIdx
;

Defect of this method: The premise is that the tree structure has several layers without general purpose. The current method is only applicable to two layers of tree structure, with the focus on providing a solution to the problem: create data based on existing data

BitsCN.com
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.