Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Parent-Child relationship when Parent and Child are stored in same table

I have SQL Server table structure like below:

ID    Name     ParentID
-----------------------
1     Root       NULL
2     Business   1
3     Finance    1
4     Stock      3

I want to display the details in my web page like

ID    Name     ParentName
-------------------------
1     Root      -
2     Business  Root
3     Finance   Root
4     Stock     Finance    

How can I construct my SQL query?

like image 749
kirikamal Avatar asked Nov 07 '10 03:11

kirikamal


People also ask

How would you describe the relationship between parent and child tables?

Child tables and parent tables are just normal database tables, but they're linked in a way that's described by a parent–child relationship. It's usually used to specify where one table's value refers to the value in another table (usually a primary key of another table). For example, imagine a news article.

How do you query a parent child relationship in SQL?

To find out who that child's parent is, you have to look at the column parent_id , find the same ID number in the id column, and look in that row for the parent's name. In other words, Jim Cliffy has no parents in this table; the value in his parent_id column is NULL .

Can a child table have two parent tables?

It depends. In general, you would like to have foreign key relationships. If there is only one comment allowed per question/answer, then it is easy. A commentId goes in each of the tables, Questions and Answers .


2 Answers

try this...

SELECT a.ID, a.Name, b.Name AS 'ParentName'
FROM TABLE AS a LEFT JOIN TABLE AS b on a.ParentID = b.ID

With the left join, the query will not find anything to join for the NULL and return blank for the ParentName column.

EDIT:

If you do not want the 'Parent' column to be blank, but want to show a '-' dash then use this query.

SELECT a.ID, a.Name, COALESCE(b.Name,'-') AS 'ParentName'
FROM TABLE AS a LEFT JOIN TABLE AS b on a.ParentID = b.ID
like image 57
Eric Avatar answered Sep 28 '22 04:09

Eric


Assuming SQL Server 2005+, use a recursive CTE like this:

WITH hierarchy AS (
  SELECT t.id,
         t.name,
         t.parentid,
         CAST(NULL AS VARCHAR(50)) AS parentname
    FROM YOUR_TABLE t
   WHERE t.parentid IS NULL
  UNION ALL
  SELECT x.id,
         x.name,
         x.parentid,
         y.name
    FROM YOUR_TABLE x
    JOIN hierarchy y ON y.id = x.parentid)
SELECT s.id,
       s.name,
       s.parentname
  FROM hierarchy s

The CASTing of the NULL might look odd, but SQL Server defaults the data type to INT unless specified in a manner like you see in my query.

like image 39
OMG Ponies Avatar answered Sep 28 '22 04:09

OMG Ponies