SQL Select statement?

September 3, 2009 - 1:03 am

I need a SQL select statement and not sure how to write it.

My table is in this format

ID Name ParentID
1 ABCD 0
2 EFGH 1
3 IJKL 2
4 MNOP 3

I need to pull off a standard select statement like
Select Name From MyTable Where ID > 1
but………
I also need to select the parent ID’s name too by searching within the same table

So something like Select Name, ParentName (based on parentID) FROM MyTable Where ID >1

Basically what Mikey said. When you’re writing your FROM clause, you do something like this…

FROM MyTable AS A1 INNER JOIN MyTable AS A1 ON A1.ParentID = A2.ID

The whole query then, would look like this:

SELECT A1.Name, A2.Name AS ParentName FROM MyTable AS A1 INNER JOIN MyTable AS A2 ON A1.ParentID = A2.ID WHERE A1.ID > 1

3 Responses to “SQL Select statement?”

  1. mikeydred Says:

    SELECT A1.* , A2.Name
    FROM YOURTABLE A1 JOIN YOURTABLE A2 ON ID = PARENTID

    This is very rough because I’m not great at SQL but you give two refs to the same table and then treat them a seperate entities
    References :

  2. emb3rx Says:

    Basically what Mikey said. When you’re writing your FROM clause, you do something like this…

    FROM MyTable AS A1 INNER JOIN MyTable AS A1 ON A1.ParentID = A2.ID

    The whole query then, would look like this:

    SELECT A1.Name, A2.Name AS ParentName FROM MyTable AS A1 INNER JOIN MyTable AS A2 ON A1.ParentID = A2.ID WHERE A1.ID > 1
    References :

  3. doug a Says:

    Select Name,ParentName
    From MyTable
    Where ID > 1

    Cut and Paste that into your SQL Query anaylser.
    References :

Leave a Reply