简体   繁体   中英

SQL: Get parent and grandparent (CTE or Derived Table)?

I have two tables to join: tb_assets and tb_locations. Locations is a hierarchy of locations. So an asset may be assigned to "Building A", which may have a parent location of "San Francisco", which may have a parent of "United States"

When I query for an asset, I want to get the parent name, and that location's parent name as well.

Here is the table layout:

桌子布置

So using the following, I can easily get the parent name of the current asset, but I've played with derived tables and CTEs and I can't seem to wrap my head around the proper way to accomplish this.

SELECT f_assetname, f_locationname
FROM tb_assets
LEFT JOIN tb_locations on f_assetlocationID = f_locationID

Here is some sample data

tb_assets

f_assetID        f_assetname        f_assetlocationID
------------------------------------------------------
1                Building A         1
2                Building B         2

tb_locations

f_locationID     f_locationname     f_locationparentID
------------------------------------------------------
101              United States      NULL
102              San Francisco      101

Using the SQL above, we return the following:

f_assetname      f_locationname
----------------------------------------
Building A       San Francisco
Building B       San Francisco

The output I would like to have would be:

f_assetname      f_locationname         f_locationparentname
--------------------------------------------------------------
Building A       San Francisco          United States
Building B       San Francisco          United States

Any assistance is appreciated in advance, sincerely.

Thanks, Beems

Just add another join

SELECT a.f_assetname, p.f_locationname as parent, gp.f_locationname as grandparent
FROM tb_assets a
LEFT JOIN tb_locations p on a.f_assetlocationID = p.f_locationID
left join tb_locations gp on gp.f_locationID = p.f_locationparentID

SQLFiddle

Use a self join

Select a.f_assetname asset, p.f_locationname parent,
     gp.f_locationname grandParent
From tb_assets a
   Left Join tb_locations p 
       On  p.locationID = a_assetlocationID
   Left Join tb_locations gp 
       On  gp.locationID = p.f_locationParentId

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