Mysql parent-child structure sorting _ MySQL

Source: Internet
Author: User
Mysql parent-child structure sorting projects often encounter parent-child structure display problems. different databases have different write methods, such as using with union in SqlServer, while Mysql does not have such convenient statements.

In the following category table, foods include pizaa, buger, and coffee, while pizza is divided into several types of cheese. how can they express their parent-child structure?

CREATE TABLE category(    id INT(10),    parent_id INT(10),    name VARCHAR(50));INSERT INTO category (id, parent_id, name) VALUES(1, 0, 'pizza'),        --node 1(2, 0, 'burger'),       --node 2(3, 0, 'coffee'),       --node 3(4, 1, 'piperoni'),     --node 1.1(5, 1, 'cheese'),       --node 1.2(6, 1, 'vegetariana'),  --node 1.3(7, 5, 'extra cheese'); --node 1.2.1

One person on stackoverflow gave a good solution:

1. create a function

Delimiter ~ Drop function getPriority ~ Create function getPriority (inID INT) returns varchar (255) DETERMINISTICbegin DECLARE gParentID int default 0; DECLARE gPriority VARCHAR (255) DEFAULT ''; SET gPriority = inID; SELECT parent_id INTO gParentID FROM category where id = inID; WHILE gParentID> 0 DO/* 0 is the root */SET gPriority = CONCAT (gParentID ,'. ', gPriority); SELECT parent_id INTO gParentID FROM category where id = gParentID; end while; RETURN gPriority; end ~ Delimiter;
2. the result of calling the function is the result of sorting out the order.
SELECT * FROM category ORDER BY getPriority(ID);

☆The restriction of the getPriority function is that all data tracing must have a unique ancestor. The tree structure cannot contain multiple trees.

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.