条件连接sql如何连接

p3rjfoxz  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(334)

我正在研究sql,我有两个表表1和表2。我想加入一个名为product的列,该列有时在另一个表上没有匹配项,但在另一个列上可能有匹配项。如果表1中的一行在第二个表中没有匹配项,那么我想在另一列上进行联接。这可以做条件连接吗?
谢谢!

zynd9foi

zynd9foi1#

我想你想要:

select t2.*, coalesce(t1.location, t1n.location) as location
from table2 t2 left join
     table1 t1
     on t2.product2 = t1.product1 left join
     table1 t1n
     on t2.product2 = t1n.new_prod_name and t1.product1 is null;
5cg8jx4n

5cg8jx4n2#

不能有条件地联接,但可以联接两者,然后有条件地选择返回值。我没有这方面的任何样本数据,但我会尝试一下。
请参阅此处的完整示例。

Select t1_id
     , coalesce(t2.product2,t2n.product2,t1.product1) product
     , t1.location
     , coalesce(t2.quantity,t2n.quantity) product
     , coalesce(t2.adate,t2n.adate) "date"  
  from table1       t1 
  Left join table2  t2 
         on (t2.product2 = t1.product1)  
  left join  table2 t2n
         on (t2n.product2 = t1.new_product_name)
order by t1_id;

相关问题