自联接产生错误结果-SQL

时间:2019-01-06 22:43:25

标签: sql sql-server

我有2张桌子。

  1. Client_packet:

enter image description here

  1. 程序:

enter image description here

在这2个表中,我想找到数据包ID和父数据包ID。

所需结果:

enter image description here

上个月的链接:https://rextester.com/GXQ46948-我的试用代码在此链接中。

试用代码:

select pd.CID, pd.packet_id,pd2.packet_id,pd.packet_status
from #package_details pd
join #Program p on p.PID = pd.program_id
join #package_details pd2 on pd.CID = pd2.CID and pd2.program_id=p.parent_prog_id  --parent episode
join #Program p2 on p2.PID=pd2.program_id

此自连接产生错误的结果。有帮助吗?!

2 个答案:

答案 0 :(得分:2)

看来您的加入是错误的:

select pd.CID, pd.packet_id,pd2.packet_id,pd.packet_status
from #package_details pd
join #Program p on p.PID = pd.program_id
-- I think the wrong part of code was here as you should not link per ID
join #package_details pd2 on pd2.program_id=p.parent_prog_id  --parent episode
join #Program p2 on p2.PID=pd2.program_id

答案 1 :(得分:1)

您可以在联接中添加另一个子句以获得预期的输出。由于ZLK和Ben已经指出了连接问题,因此您可以确保它处于相同状态,并且可以通过这种方式获得输出。

 select pd.CID, pd.packet_id,pd2.packet_id as ParentpacketID,pd.packet_status from   
 #package_details pd
 join #Program p on p.PID = pd.program_id
 join #package_details pd2 on pd.CID = pd2.CID and  pd2.program_id=p.parent_prog_id 
 and pd2.packet_status = pd.packet_status  
 join #Program p2 on p2.PID=pd2.program_id  --not sure if you need this join as you are not selecting anything from this, and the output remains same without this join too. 

输出:

 CID    packet_id   ParentpacketID  packet_status
 1001   20            21                 OPEN
 1001   15            16                 CLOSED