【问题标题】:Self join when using more than 1 table使用超过 1 个表时的自联接
【发布时间】:2020-01-22 12:57:42
【问题描述】:

-- BEFORE -- 此自连接中使用的所有字段都来自同一个“Prime”表:

SELECT
    a.*,
    b.column1 as column1b,
    b.column2 as column2b,
    b.column3 as column3b,
    b.column4 as column4b,
    b.column5 as column5b,
    b.next_column5 as next_column5b,
    b.column6 as column6b,
    b.column7 as column7b,
    b.column8 as column8b,          -- 
    b.column9 as column9b,
    b.column10 as column10b,
    CASE
       WHEN a.column5 > b.column5 THEN a.column5
       WHEN b.column5 > a.column5 THEN b.column5
       ELSE a.column5
    END AS TheStart,
    CASE 
       WHEN b.next_column5 > today() AND b.column8 = 0
          THEN 1
          ELSE 0
    END AS TheEnd
FROM  
    prime a , prime b
WHERE
    a.column11 = b.column11 
    AND a.conper = b.conper 
    AND a.condtn = b.condtn 
    AND a.genass = b.genass 
    AND a.column3 IN ('A_B', 'A_nB')
    AND b.column3 = 'B' 
    AND a.prime_sum_c > 0
ORDER BY
    column11, column1, column2, column6, column7, column5

--之后--

[column8] 字段现在来自另一个名为 [OtherTable] 的表

问题:我应该如何写下新代码以继续使用 SELF JOIN 并考虑到由于 [OtherTable].column8 而我们现在正在处理 2 个不同的表

【问题讨论】:

标签: sql self-join


【解决方案1】:

您可以像这样修改查询以使用join

select 
a.*,
b.column1 as column1b,
b.column2 as column2b,
b.column3 as column3b,
b.column4 as column4b,
b.column5 as column5b,
b.next_column5 as next_column5b,
b.column6 as column6b,
b.column7 as column7b,
o.column8 as column8b,          -- from OtherTable
b.column9 as column9b,
b.column10 as column10b,
CASE
   WHEN a.column5 > b.column5 THEN a.column5
   WHEN b.column5 > a.column5 THEN b.column5
   ELSE a.column5
END AS TheStart,
case 
 when b.next_column5 > today() and o.column8 = 0
 then 1
 else 0
end as TheEnd
from prime a 
inner join prime b on a.column11 = b.column11 
                     and a.conper = b.conper 
                     and a.condtn = b.condtn 
                     and a.genass = b.genass 
left join OtherTable o on <<your join condition>> -- join with OtherTable here
where a.column3 in ('A_B','A_nB')
and b.column3 = 'B' 
and a.prime_sum_c > 0
order by column11, column1, column2, column6, column7, column5

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多