【问题标题】:Mysql - Finding grand parents with from category treeMysql - 从类别树中查找祖父母
【发布时间】:2017-06-24 13:57:23
【问题描述】:

当我们将子类别的 id 作为 mysql 查询中的 where 条件时,我想在状态设置为 1 的树中获取祖父母

类别

id | parent_id | name        | status
-------------------------------------
1  | 0         | Cars        |0
2  | 0         | Planes      |0
3  | 1         | Hatchbacks  |1 
4  | 1         | Convertibles|1
5  | 2         | Jets        |1
6  | 3         | Peugeot     |0
7  | 3         | BMW         |1
8  | 6         | 206         |0
9  | 6         | 306         |0

在这个例子中,如果我有 id = 8 那么结果会得到 id=3 的记录

【问题讨论】:

  • 提示:你需要两个自连接。
  • 似乎与 PHP 无关。

标签: php mysql sql


【解决方案1】:

如前所述,双重自联接正在工作。 如果没有可用的祖父母项,则不会返回任何行 就像您的示例中的 Id = 4 一样,有一个父项,但没有祖父项

SELECT catgrandparent.*
  FROM category catchild
 INNER JOIN category catparent
    ON catchild.parent_id = catparent.id
 INNER JOIN category catgrandparent
    ON catparent.parent_id = catgrandparent.id

【讨论】:

    【解决方案2】:

    根据上述问题的描述,请尝试执行以下SQL查询

    例如获取类别 id 8 的祖父母

    select c.* from category as a join category b on a .parent_id=b.id 
     join category c on c.id=b.parent_id where a.id=8
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多