SQL,如何在第二个表中连接三个没有外部参照的表?

时间:2017-06-23 16:53:15

标签: mysql sql join

我有以下格式的三个表:

表1

Plan_ID  Plan_Code   Plan_Description  Location_ID
 1          A           Plan A             1

表_2(现在是行)

ID   Plan_ID  Procedure_ID   Discount

TABLE_3

Procedure_ID   Procedure_Name  Procedure_Fee     Location_ID
   1                 P1             10              1
   2                 P2             20              1 
   3                 P3             30              1
   4                 P3             30              2

所以我需要编写一个查询,在传递Plan_Id时输出以下结果,并匹配表1和3 Location_ID:

Plan_ID  Plan_Code   ID   Procedure_ID  Procedure_Name  Procedure_Fee Discount
   1          A       0        1               P1            10          0
   1          A       0        2               P2            20          0
   1          A       0        3               P3            30          0

同样在表2中,如果我们有交叉引用行

ID   Plan_ID  Procedure_ID   Discount
 1      1          2            5

下面应该是查询输出:

Plan_ID  Plan_Code   ID   Procedure_ID  Procedure_Name  Procedure_Fee Discount
   1          A       0        1               P1            10          0
   1          A       1        2               P2            20          5
   1          A       0        3               P3            30          0

到目前为止,我已经尝试过:

declare @planID int =1 
SELECT t1.Plan_ID, 
    t1.Plan_Code,
    t2.ID,
    t3.Procedure_ID,
    t3.Procedure_Name,
    t3.Procedure_Fee,
    t2.Discount
FROM table1 tl
LEFT JOIN table2 t2 
    on t1.Plan_ID=t2.Plan_ID  
RIGHT JOIN table3 t3 
    ON t2.Procedure_ID  = t3.Procedure_ID and t1.Location_Id=t3.LocationID
where t1.Plan_Id = @planID

但是由于where条件,查询不会输出任何结果,但是当我在第一次连接中替换where条件时,我得到的输出不正确。我尝试使用不同的表序列和连接选项运行查询,但无法成功。

1 个答案:

答案 0 :(得分:1)

由于表2可能有也可能没有匹配的行,您需要处理表1和表2之间匹配中缺少的数据:

declare @planID int = 1;

SELECT t1.Plan_ID, 
    t1.Plan_Code,
    if(t2.ID IS NULL,0,t2.ID) as `ID`,
    t3.Procedure_ID,
    t3.Procedure_Name,
    t3.Procedure_Fee,
    IF(t2.Discount IS NULL,0,t2.Discount) as `Discount`
FROM table1 tl
JOIN table3 t3 
    ON t1.Location_Id = t3.LocationID
LEFT JOIN table2 t2 
    ON t2.Procedure_ID  = t3.Procedure_ID and t1.Plan_ID = t2.Plan_ID  
where t1.Plan_Id = @planID;