ABY*_*ABY 3 sql join outer-join google-bigquery
我想对具有多个条件的两个表执行完全外连接,以生成两个表中的所有匹配记录以及不匹配的记录。Tbl1 是一个更大的表,有 21 M 条记录,Tbl2 有 5k 行,如下面的示例查询。但外连接无法使用 OR 条件执行,因为出现错误“如果没有连接两侧字段相等的条件,则无法使用 FULL OUTER JOIN”。在这种情况下,编写单独的查询,然后使用 COALESCE 是唯一的解决方案吗?我不确定如何实施这个解决方案。寻求任何帮助来解决这个问题。
SELECT
*
FROM
`myproject.table1` as t1
Full Outer JOIN
`myproject.table2` as t2
ON
(
t1.Camp1ID = t2.ID
OR t1.Camp2ID = t2.ID
OR t1.Camp3ID = t2.ID
OR t1.Camp4ID = t2.ID
OR t1.Camp5ID h = t2.ID
OR t1.Camp6ID = t2.ID
OR t1.Camp7ID = t2.ID
OR t1.Camp8ID = t2.ID
OR t1.Camp9ID = t2.ID
OR t1.Camp10ID = t2.ID
OR t1.Camp11ID = t2.ID
OR t1.Camp12ID = t2.ID
OR t1.Camp13ID = t2.ID
OR t1.Camp14ID = t2.ID
OR t1.Camp15ID = t2.ID
OR t1.Camp16ID = t2.ID
)
Where
t1.Date BETWEEN PARSE_DATE('%m/%d/%y', t2.StartDate) AND PARSE_DATE('%m/%d/%y', t2.EndDate)
Run Code Online (Sandbox Code Playgroud)
示例代码 -
Tbl1:
EmpNo EmpITPrj EmpFinPrj EmpHRPrj EmpIntPrj Date
1 IT101 null null null 2019-09-01
2 null Fin101 null null 2001-06-05
3 null null HR101 null 2005-11-25
4 null null null Int501 2010-10-15
5 null null null Int105 2019-01-10
Tbl2:
PrjID PrjStartDate PrjEndDate
Fin101 06/01/2005 08/14/2005
IT102 07/11/2006 10/30/2006
Int105 09/15/2019 10/01/2019
EmpNo EmpITPrj EmpFinPrj EmpHRPrj EmpIntPrj Date PrjID PrjStartDate PrjEndDate
1 IT101 null null null 2019-09-01 null null null
2 null Fin101 null null 2001-06-05 Fin101 06/01/2005 08/14/2005
3 null null HR101 null 2005-11-25 null null null
4 null null null Int501 2010-10-15 null null null
5 null null null Int105 2019-01-10 Int105 09/15/2019 10/01/2019
null null null null null null IT102 07/11/2006 10/30/2006
Run Code Online (Sandbox Code Playgroud)
只需将您的条件从ON移至WHERE并可选择优化所有这些 OR,如下所示
t2.ID IN (t1.Camp1ID,t1.Camp2ID,t1.Camp3ID,t1.Camp4ID,t1.Camp5ID,t1.Camp6ID,t1.Camp7ID,t1.Camp8ID,t1.Camp9ID,t1.Camp10ID,t1.Camp11ID,t1.Camp12ID,t1.Camp13ID,t1.Camp14ID,t1.Camp15ID,t1.Camp16ID)
Run Code Online (Sandbox Code Playgroud)
所以你的最终查询可能如下所示
SELECT *
FROM `myproject.table1` as t1
Full Outer JOIN `myproject.table2` as t2
ON TRUE
Where t1.Date BETWEEN PARSE_DATE('%m/%d/%y', t2.StartDate) AND PARSE_DATE('%m/%d/%y', t2.EndDate)
And t2.ID IN (t1.Camp1ID,t1.Camp2ID,t1.Camp3ID,t1.Camp4ID,t1.Camp5ID,t1.Camp6ID,t1.Camp7ID,t1.Camp8ID,t1.Camp9ID,t1.Camp10ID,t1.Camp11ID,t1.Camp12ID,t1.Camp13ID,t1.Camp14ID,t1.Camp15ID,t1.Camp16ID)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2910 次 |
| 最近记录: |