【问题标题】:SQL, how to join three tables with no xref in second table?SQL,如何在第二个表中连接三个没有外部参照的表?
【发布时间】:2017-11-27 07:56:09
【问题描述】:

我有以下格式的三个表格:

表_1

Plan_ID  Plan_Code   Plan_Description  Location_ID
 1          A           Plan A             1

Table_2(当前为行)

ID   Plan_ID  Procedure_ID   Discount

表_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

同样在 Table_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 条件时,我得到不正确的输出。我尝试使用不同的表序列和连接选项运行查询,但未能成功。

【问题讨论】:

    标签: mysql sql join


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2018-05-05
      相关资源
      最近更新 更多