首页 > 解决方案 > BigQuery 完全连接两个表,没有要连接的列

问题描述

我的标题有点误导,可能无法清楚地解释我想要做什么,但我希望我下面的例子能做到。我有两张桌子:

t1

col1    col2 
a       a
a       c
b       a
b       d
c       a
c       d

t2

team   game
mazs      1
mazs      2
doos      1
bahs      3
...

t2是一张很长的桌子,里面有很多球队和比赛,而t1完整显示 - 一张有 6 行的桌子,具有字母 a、b、c、d 的组合。请注意,这t1不是一个完整的 a、b、c、d 配对列表,只有出现的 6 行中的配对。

我想创建一个如下所示的表:

output

team  game  col1  col2
mazs     1     a     a
mazs     1     a     c
mazs     1     b     a
mazs     1     b     d
mazs     1     c     a
mazs     1     c     d
mazs     2     a     a
mazs     2     a     c
mazs     2     b     a
mazs     2     b     d
mazs     2     c     a
mazs     2     c     d

这里发生的情况是,对于 中的每一行,在t2中有 6 行output,对于来自 的每个col1, col2配对都有一行t1

t1t2通过以下查询在我这边创建:

SELECT col1, col2 FROM sometable GROUP BY col1, col2
SELECT DISTINCT team, game FROM anothertable 

第一个查询创建t1,第二个查询创建t2. 非常感谢您对此(或更好的标题)的任何帮助,谢谢!

标签: google-bigquery

解决方案


它被称为CROSS JOIN,见下面的例子:

With t1 as (
select 'a' col1, 'a' col2 union all
select 'a' col1, 'c' col2 union all
select 'b' col1, 'a' col2 union all
select 'b' col1, 'd' col2 union all
select 'c' col1, 'a' col2 union all
select 'c' col1, 'd' col2),
t2 as (
select 'mazs' team, 1 game union all
select 'mazs' team, 2 game union all
select 'doos' team, 1 game union all
select 'bahs' team, 3 game
) 

SELECT * FROM t2 cross join t1;

输出:

+------+------+------+------+
| team | game | col1 | col2 |
+------+------+------+------+
| mazs |    1 | a    | a    |
| mazs |    1 | a    | c    |
| mazs |    1 | b    | a    |
| mazs |    1 | b    | d    |
| mazs |    1 | c    | a    |
| mazs |    1 | c    | d    |
| mazs |    2 | a    | a    |
| mazs |    2 | a    | c    |
| mazs |    2 | b    | a    |
| mazs |    2 | b    | d    |
| mazs |    2 | c    | a    |
| mazs |    2 | c    | d    |
| doos |    1 | a    | a    |
| doos |    1 | a    | c    |
| doos |    1 | b    | a    |
| doos |    1 | b    | d    |
| doos |    1 | c    | a    |
| doos |    1 | c    | d    |
| bahs |    3 | a    | a    |
| bahs |    3 | a    | c    |
| bahs |    3 | b    | a    |
| bahs |    3 | b    | d    |
| bahs |    3 | c    | a    |
| bahs |    3 | c    | d    |
+------+------+------+------+

推荐阅读