【问题标题】:how to retrive data from a table using mysql which has a parent child relation ship?如何使用具有父子关系的mysql从表中检索数据?
【发布时间】:2014-08-05 10:49:29
【问题描述】:

我有一个包含 3 行的表,例如 cat_id、cat_name、cat_parent。

我的桌子看起来像:

-------------------------------------
|cat_id   |   cat_name   | cat_parent
-------------------------------------
| 1       |  Electronics | 0
| 2       |  mobile      | 1
| 3       |  ac          | 1
| 4       |  Furniture   | 0
| 5       |  Chair       | 4

我想使用 MySql 单查询选择父类别及其子类别。

有什么帮助吗?

【问题讨论】:

  • 你有什么尝试
  • 使用self join点击此链接http://www.tutorialspoint.com/sql/sql-self-joins.htm了解
  • 子表和父表之间的独特之处
  • 已知或未知的深度/儿童数量?
  • 非常感谢@Rahul 和Agha Umair Ahmed。 :)

标签: php mysql


【解决方案1】:

对于 2 或 3 的深度:

SELECT
  l0.cat_name,
  l1.cat_name,
  l3.cat_name
FROM      categories l0
JOIN      categories l1 ON l0.cat_id = l1.cat_parent
LEFT JOIN categories l2 ON l1.cat_id = l2.cat_parent

【讨论】:

    【解决方案2】:
    SELECT
        A.cat_id as cat_id,
        A.cat_name child_id,
        A.cat_parent as parent_id,
        B.cat_name as parent_name
    FROM `cat` A
    JOIN `cat` B ON 
        A.cat_parent=B.cat_id
    

    【讨论】:

      【解决方案3】:

      试试这个:

      select
          a.cat_id,
          a.cat_name,
          a.cat_parent,
          b.cat_name as child
      from
          table as a,
          table as b
      where
          a.cat_parent = b.cat_id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多