如果没有更严格的条件,则有条件地回退到不同的加入条件

时间:2019-04-24 20:50:49

标签: sql sql-server join inner-join

我有2个表j和c。

两个表都具有端口和秒列,并且JOIN ON j.ports = c.ports和c.sec = j.sec。

对于j.port = 'ABC',如果相同端口没有c.sec = j.sec,则请加入LEFT(c.sec, 6) = LEFT(j.sec, 6)

对于其他j.ports,我只想加入ON j.ports = c.ports and c.sec = j.sec

我该怎么做?

示例数据

表c

+------+------------+------------+
| Port |    sec     |   Other    |
+------+------------+------------+
| ABC  | abcdefghij |  ONE       |
| ABC  | klmnop     |  TWO       |
| LMN  | qwertyuiop |  THREE     |
| XYZ  | asdfghjkl  |  FOUR      |
+------+------------+------------+

表j

+------+------------+
| Port |    sec     |
+------+------------+
| ABC  | abcdefxxxx |
| ABC  | klmnop     |
| LMN  | qwertyuiop |
| XYZ  | zxcvbnm    |
+------+------------+

已编辑:所需结果

+------+------------+------------+
| Port |    sec     |  other     |
+------+------------+------------+
| ABC  | abcdefghij |  ONE       |  --> mactching on sec's 1st 6 characters 
| ABC  | klmnop     |  TWO       |  --> mactching on sec
| LMN  | qwertyuiop |  THREE     |  --> mactching on sec
+------+------------+------------+

3 个答案:

答案 0 :(得分:0)

这是有条件的加入:

select t1.*, t2.*
from j t1 inner join c t2
on t2.ports = t1.ports and
  case 
    when exists (select 1 from c where sec = t1.sec) then t1.sec 
    else left(t1.sec, 6) 
  end =
  case 
    when exists (select 1 from c where sec = t1.sec) then t2.sec 
    else left(t2.sec, 6) 
  end

我质疑它的效率,但我认为它可以满足您的需求。
参见demo

答案 1 :(得分:0)

您可以执行两个外部联接,然后执行isull类型的操作。在Oracle中,nvl是sqlserver的isull

with c as 
(
    select 'ABC' port, 'abcdefghij' sec from dual
    union all select 'ABC', 'klmnop' from dual 
    union all select 'LMN', 'qwertyuiop' from dual
    union all select 'XYZ', 'asdfghjkl' from dual
),
j as 
(
    select 'ABC' port, 'abcdefxxxx' sec from dual
    union all select 'ABC', 'klmnop' from dual 
    union all select 'LMN', 'qwertyuiop' from dual
    union all select 'XYZ', 'zxcvbnm' from dual
)
select c.port, c.sec, nvl(j_full.sec, j_part.sec) j_sec
from c
     left outer join j j_full on j_full.port = c.port and j_full.sec = c.sec
     left outer join j j_part on j_part.port = c.port and substr(j_part.sec,1,6) = substr(c.sec,1,6)
order by 1,2

答案 2 :(得分:0)

一种方法是只对不太严格的谓词进行内部联接,然后在c.port = 'ABC'和更严格的条件与特定c.port, c.sec组合匹配的情况下,使用排名函数丢弃不需要的行

with cte as
(
select c.port as cPort, 
       c.sec as cSec, 
       c.other as other,
       j.sec as jSec, 
       RANK() OVER (PARTITION BY c.port, c.sec ORDER BY CASE WHEN c.port = 'ABC' AND j.sec = c.sec THEN 0 ELSE 1 END) AS rnk
from c inner join  j on left(j.sec,6) = left(c.sec,6)
)
SELECT cPort, cSec, other, jSec
FROM cte 
WHERE rnk = 1