在bigquery中连接多个表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在bigquery中连接多个表相关的知识,希望对你有一定的参考价值。

我希望能够在bigquery中加入多个表。加入两个是非常微不足道的。

SELECT
t1.field1 AS field1,
t2.field2 AS field2,
t1.field3 AS field3
FROM [datasetName.tableA] t1
JOIN [datasetName.tableB] t2
ON t1.somefield = t2.anotherfield

但是,如果我想加入三张或更多桌子怎么办?我可以这样做吗?

SELECT
t1.field1 AS field1,
t2.field2 AS field2,
t1.field3 AS field3,
t3.field4 as field4
FROM [datasetName.tableA] t1
JOIN [datasetName.tableB] t2
JOIN [datasetName.tableC] t3
ON t1.somefield = t2.anotherfield AND t1.somefield=t3.yetanotherfield

我试过了,但它不起作用。我想我需要做点什么

SELECT 
t12.field1 as field1,
t12.field2 as field2,
t3.field3 as field3,
FROM
(SELECT
t1.field1 AS field1,
t2.field2 AS field2,
t1.field3 AS field3
FROM [datasetName.tableA] t1
JOIN [datasetName.tableB] t2
ON t1.somefield = t2.anotherfield) t12
JOIN
[datasetName.tableC] t3
ON t12.field1 = t3.field1 

但有没有更简单的方法来实现这一目标?

谢谢,布拉德

答案

我想你正在寻找类似下面的东西

SELECT
  t1.field1 AS field1,
  t2.field2 AS field2,
  t1.field3 AS field3,
  t3.field4 AS field4
FROM [datasetName.tableA] t1
JOIN [datasetName.tableB] t2 ON t1.somefield = t2.anotherfield
JOIN [datasetName.tableC] t3 ON t1.somefield = t3.yetanotherfield
另一答案

您还可以在标准SQL中使用USING(field)表示法。这实际上只是@ mikhail-berlyant回答的糖。文件here

#standardSQL
SELECT
  t1.field1 AS field1,
  t2.field2 AS field2,
  t1.field3 AS field3
FROM `datasetName.tableA` t1
JOIN `datasetName.tableB` t2 USING(commonfield_AB)
JOIN `datasetName.tableC` t3 USING(commonfield_AC)

以上是关于在bigquery中连接多个表的主要内容,如果未能解决你的问题,请参考以下文章

BigQuery 中的多个左连接

BigQuery 避免多个子查询

如何使用 dplyr 和 bigquery 从 Bigquery 数据集中的多个表中进行选择?

在 Bigquery 中为多个 CSV 文件自动创建表

在大查询中连接多个表

BigQuery:从表连接引起的子选择中删除记录