MySQL recursive query, infinite level of the subordinate menu

Source: Internet
Author: User

mysql recursive query,MySQL from the subclass ID query all the parent class (do unlimited classification often used)

Because MySQL does not support recursive query syntax similar to Oracle with ... connect
It was thought that a similar query would either use a stored procedure or only write a recursive query with a program.

Now I find out that a SQL statement can be done.

Let's look at the structure of the data table as follows:

ID Name parent_id

---------------------------
1 Home 0
2 about 1
3 Contact 1
4 Legal 2
5 Privacy 4
6 Products 1
7 Support 1
I want the request is based on a classification ID (this classification ID may be a subcategory), get all the parent category, the following is the corresponding SQL:

SELECT T2.id, T2.name
From (
SELECT
@r as _id,
(SELECT @r: = parent_id from table1 WHERE id = _id) ASPARENT_ID,
@l: = @l + 1 as lvl
From
(SELECT @r: = 5, @l: = 0) VARs,
Table1 h
WHERE @r<> 0) T1
JOIN table1 T2
On t1._id = T2.id
ORDER by T1.lvl DESC;

MySQL recursive query, infinite level of the subordinate menu

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.