简体   繁体   中英

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

I have a table with 3 rows like cat_id,cat_name,cat_parent.

My table will look like:

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

I would like to select the parent category and its child using MySql single query.

any help?

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

Try this:

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

For a depth of 2 or 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM