Selecting records in order of parent id

前端 未结 4 887
天涯浪人
天涯浪人 2020-12-31 17:14

Simple question.. just can\'t get the result set in the order I need :p

I have a table \"categories\"

id    | name     | parent
1       apple      0
         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 17:46

    For a simple, perhaps suboptimally-scalable solution, I recommend hard-coding this with the maximum number of levels you will have:

    For 2 levels only:

    SELECT p2.name as `Parent name`, p1.*
    FROM categories p1
    LEFT JOIN categories p2 on p1.categories_id = p2.id
    

    You're really asking about sorting, so I'd recommend generating a "path"-like string: (see below for sample output of this query)

    SELECT Concat(If(isnull(p2.name),"",Concat("/",p2.name)),"/",p1.name) as `generated path`, p2.name as `Parent name`, p1.*
    FROM categories p1
    LEFT JOIN categories p2 on p1.parent_id = p2.id
    order by `generated path`
    

    For 3 levels, though your data doesn't have this yet -- path omitted because it will get ugly :)

    SELECT p3.name as `Grandparent name`, p2.name as `Parent name`, p1.*
    FROM categories p1
    LEFT JOIN categories p2 on p1.categories_id = p2.id
    LEFT JOIN categories p3 on p2.categories_id = p3.id
    

    A more comprehensive solution for quickly selecting all items in a particular category at any level, which does require some work on all writes, is implementing a 'right' and 'left' numbering concept. But, further discussion on that is almost certainly going beyond the scope of what you're asking. However, that's the only good way in my experience to make this kind of self-referencing table very useful if it's going to get big (maybe after 1000+ rows with 3 to 10 levels).

    Addendum: sample output from the second query:

    generated path         Parent name         id         name         parent_id
    ----------------------------------------------------------------------------
    /apple                                      1         apple                0
    /apple/lisa                  apple          5         lisa                 1
    /apple/mac                   apple          2         mac                  1
    /atari                                      3         atari                0
    /atari/st                    atari          4         st                   3
    

提交回复
热议问题