简体   繁体   中英

Mysql query to retrieve child and parent data from the same table

I have a mysql table as in below figure.

在此处输入图片说明

Now i want to query to this table so that i get data as follows

在此处输入图片说明

If there is no parent then parent must be populated as "NONE" or Empty. How do i achieve this query? Is this even possible? I discussed this with my friend but still no answer. Any help would be appreciated. Thanks

You have to join your table with itself, using a LEFT JOIN that will return all rows from the left table and the rows from the second table that match the join condition:

Select
  t1.ID,
  t1.Name,
  t2.Name AS Parent,
  t1.Remarks
From
  yourtable t1 LEFT JOIN yourtable t2
  ON t1.parent_id = t2.id

you could also use COALESCE(t2.name, 'NONE') AS Parent to return the string NONE when there's no match.

In MS SQL Server, you can use CTE (Common Table Expression) - hierarchical query to retrieve child and leaf level childs. But my sql does not support CTE.

Please refer this question which represents that MySQL does not support CTE.
This answer will help you to get all the child and child of that child. You need to create hierarchical query.

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