如何从一个表中检索数据使用mysql有一个父子关系


how to retrive data from a table using mysql which has a parent child relation ship?

我有一个表,有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单一查询。

帮忙吗?

当深度为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
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

试试这个:

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