繁体   English   中英

在可能需要排名的多个条件下进行SQL连接

[英]SQL joining on multiple conditions where ranking may be required

问题

我有两个需要在多个条件下联接的表。 在大多数情况下,这很简单,除了最后一个条件:

Select * from tableA
left outer join tableB on condition1
                        OR condtion2
                        OR condtion3
                        OR condtion4
                        OR <the record with the most recent tableB.date before tableA.date that has not already been joined in the above conditions>

我尝试了一些选择,例如使用交叉路径,嵌套查询和case语句都无济于事。 (似乎总是在进行1:M比赛,或者比赛不正确)

有什么方法可以确保只有1:1映射(即,如果表B中的记录已经通过先前的条件映射到tableA中的记录,然后在最后一个条件下不匹配?)

例:

表A :(决定)

ID
-----
DEC1
DEC2
DEC3a
DECX

TableB :(任务)

ID    
-----
TASK1
TASK2
TASk3
TASK4

预期输出:

DecID|TaskID  
------------  
DEC1 |TASK1
DEC2 |TASk2
DEC3a|TASK3
DECX |TASK4

前3行由现有条件覆盖。 但是DECX可以映射到任何尚未映射的任务

Select * from tableA
left outer join tableB 
  on condition1
  OR condtion2
  OR condtion3
  OR condtion4
UNION
Select * from tableA
left outer join tableB 
  on <the record with the most recent tableB.date before tableA.date that has not already been joined in the above conditions>
  AND NOT condition1
  AND NOT condition2
  AND NOT condition3
  AND NOT condition4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM