首页 > 解决方案 > 如何连接三个表并将空白字段设置为空?

问题描述

在此处输入图像描述

我用full joinandleft join来加入Person,TasksTask表。屏幕上显示的结果导致行数大于六。未设置的字段具有价值NULL,这很好。

使用这样可以获得预期的输出joins,但是有必要使用允许连接公共字段的子句。我怎样才能做到这一点?

标签: sql

解决方案


ACROSS JOIN产生你想要的所有组合。然后一个简单的外连接可以检索相关的行(如果它们存在的话)。

你没有提到你正在使用的数据库,所以一个失败的标准查询就可以了。例如(在 PostgreSQL 中):

select
  row_number() over(order by p.id, t.id) as id,
  p.name,
  case when x.st is not null then t.hr end,
  x.st
from person p
cross join tasks t
left join task x on x.personid_fk = p.id and x.taskid_fk = t.id
order by p.id, t.id;

结果:

 id  name  case   st    
 --- ----- ------ ----- 
 1   Anna  null   null  
 2   Anna  null   null  
 3   Luo   13:00  true  
 4   Luo   14:00  false 
 5   John  null   null  
 6   John  null   null  

请参阅DB Fiddle上的运行示例。


推荐阅读