Getting all parent rows in one SQL query

后端 未结 7 2006
温柔的废话
温柔的废话 2020-11-27 11:59

I have a simple MySQL table thats contains a list of categories, level is determined by parent_id:

id  name    parent_id
---------------------------
1   Home         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 12:24

    I used the previous answers as examples to make smth more readable.

    SELECT  @org_id as id,
        (SELECT name FROM test.organizations WHERE id = @org_id) as name,
        (SELECT @org_id := parent_id FROM test.organizations WHERE id = @org_id) AS parent_id
    FROM (SELECT @org_id := 4) vars, test.organizations org
    WHERE @org_id is not NULL
    ORDER BY id;
    

    The result of execution looks like that:

    (just for quick) to check it yourself you need to enter values from the question into database test, table organizations

    CREATE TABLE organizations(
    id        int(11) NOT NULL AUTO_INCREMENT,
    name      varchar(45) DEFAULT NULL,
    parent_id int(11)     DEFAULT NULL,
    PRIMARY KEY (id));
    
    insert into organizations values(1, "home", null);
    insert into organizations values(2, "about", 1);
    insert into organizations values(3, "contact", 1);
    insert into organizations values(4, "legal", 2);
    insert into organizations values(5, "privacy", 4);
    insert into organizations values(6, "products", 1);
    insert into organizations values(7, "support", 1);
    

提交回复
热议问题