Select Columns using nested select statement.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bkoh
    New Member
    • Jan 2010
    • 1

    Select Columns using nested select statement.

    Hi all,

    I am populating data from a table which contain parent id which reference to itself
    E.g.: TableA - ID, Name, Desc, ParentID
    ParentID reference to ID

    I would need the result to return:
    ID, Name, Desc, ParentID, ParentName, ParentDesc

    Select statement:
    SELECT ID, Name, Desc, ParentID,
    (SELECT Name from TableA WHERE ID=ParentID) AS ParentName,
    (SELECT Desc from TableA WHERE ID=ParentID) AS ParentDesc
    FROM TableA;

    Is there any performance issue using this approach?
    Is there a better way of doing this?
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    It looks a little unconventional, and the sub-query would throw an error if there was more than one ID returned. What about
    Code:
    SELECT child.ID, child.Name, child.Desc, child.ParentID, 
    parent.Name AS ParentName,
    parent.Desc AS ParentDesc
    FROM TableA child
    JOIN TableA parent ON child.ID = parent.ParentID;
    Pleas adjust to correct parent-child field required

    Comment

    • ck9663
      Recognized Expert Specialist
      • Jun 2007
      • 2878

      #3
      Try using a recursive CTE instead.

      Happy Coding!!!

      ~~ CK

      Comment

      • nbiswas
        New Member
        • May 2009
        • 149

        #4
        Recursive CTE

        Simple Example of Recursive CTE

        Comment

        Working...