【问题标题】:MySQL Get Parent With Child Rows TogetherMySQL将父级与子行放在一起
【发布时间】:2015-10-29 04:15:48
【问题描述】:

我已经搜索过这样的问题,尽管很多问题相似,但没有准确回答我的问题,而且查询不起作用。

假设我们有下表

id     category_name     parent_id
------------------------------------
1      test              0
2      test1             0
3      new_cat           1
4      new_catx          2
5      cat5              1

我想要一个 sql 查询,其输出将是这样的

id     category_name     parent_id
------------------------------------
1      test              0
3      new_cat           1
5      cat5              1
2      test1             0
4      new_catx          2

在排序中,输出查询是根据 parent_id 排序的。 parent_id = 0 是根类别,然后是子类,然后是另一个父类和它的子类。等等

【问题讨论】:

    标签: mysql


    【解决方案1】:

    这适用于 1 级树,即只包含父母及其孩子的树:

    SELECT *
    FROM mytable
    ORDER BY CONCAT(IF(parent_id=0, '', parent_id), id)
    

    Demo here

    【讨论】:

      【解决方案2】:

      理想情况下,您应该为此使用映射表,以使您的解决方案完全可扩展。将原始表结构更改为

      id    category_name
      ---------------------
      1     test
      2     test1
      3     new_cat
      4     new_catx
      5     cat5
      

      ...并有一个父映射表,如下所示:

      id    parent_id
      ---------------------
      3     1
      4     2
      5     1
      

      那么您只需将 Giorgos Betsos 的出色查询修改为:

      select t.id, t.category_name, p.parent_id
      from testtable t left outer join parents p
          on t.id = p.id
      ORDER BY CONCAT(IF(p.parent_id is null, '', p.parent_id), t.id);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多