SQL查询父子

时间:2017-09-25 11:24:55

标签: sql sql-server

你能帮帮我吗?

Table: LOS
ID    Name         ParentID
1    Item          Null
2    Pharmacy        1
3    Consumable      1
4    Ethical         2
5    Non Ethical     2
6    MCCP            4
7    Nurse           3

Table: Item
 id  ItemName  lOS_Id   Los_Name
 123 Panadol    6       MCCP
 321 Nacl       7       Nurse


Expected Result.
ID     ItemName    ParentID   ParentName    LOS_Id  Los_Name              
123    Panadol      2         Pharmacy         6    MCCP
321    Nacl         3         Consumable       7    Nurse

说明:来自los_id的ParentID使用ID THEN加入LOS表获取parentID以查找Parent

2 个答案:

答案 0 :(得分:1)

我希望我理解正确,此查询将解决您的问题:)

select I.ID, I.ItemName, A.ParentID, A.ParentName, I.LOS_ID, I.LOS_Name from Item AS I join (
select l1.id, l1.name, l1.ParentID, l2.name as ParentName from LOS as l1 join LOS as l2 on l1.id = l2.ParentID
) as A join on I.LOS_ID = A.ID

答案 1 :(得分:1)

请看这个例子。

Declare @LOS table (ID  int,  Name  nvarchar(50), ParentID int)
Declare @Item table (ID  int,  ItemName nvarchar(50), lOS_ID  int,  lOS_Name nvarchar(50) )

Insert into @LOS values (1, 'Item',null), (2 ,'Pharmacy', 1), (3 ,'Consumable', 1), (4 ,'Ethical', 2), (5 ,'Non Ethical', 2), (6 ,'MCCP', 4)
, (7 ,'Nurse', 3)

Insert into @Item values (123, 'Panadol',6 ,'MCCP'), (321, 'Nacl',7 ,'Nurse')

select * from @LOS
select * from @Item


;with cte as
(
    select i.id, ItemName, lOS_ID, lOS_Name, lOS_ID parentid, lOS_ID parentparentid, lOS_Name parentname from @Item i
    join @los l on i.lOS_ID = l.id 
    -- where i.id = 123
    union all
    select 
        c.id, ItemName, lOS_ID, lOS_Name,  l.ID parentid,  l.ParentID parentparentid, l.Name parentname 
    from 
        cte c join @los l on c.parentparentid = l.id --and c.ParentID <> null
)
select * from cte where parentparentid = 1
order by id