CROSS JOIN超过两张桌子

时间:2016-05-27 13:24:59

标签: google-bigquery

我有三个表,t1,t2和t3。表结构和值:

t1_id | t1_k1 | t1_val
------+-------+--------
1     | k1foo | t1foo
2     | k1bar | t1bar
3     | k1baz | t1baz

t2_id | t2_k1 | t2_k2 | t2_val
------+-------+-------+--------
1     | k1foo | k2foo | t2foo
2     | k1bar | k2bar | t2bar
3     | k1baz | k2baz | t2baz

t3_id | t3_k2 | t3_val
------+-------+--------
1     | k2foo | t3foo
2     | k2bar | t3bar
3     | k2baz | t3baz

因此,对于普通的SQL,我可以在t1_k1 = t2_k1上加入t1和t2,在t2_k2 = t3_k2上加入t2和t3,即:

SELECT t1_val, t2_val, t3_val
FROM t1, t2, t3
WHERE t1_k1 = t2_k1 AND t2_k2 = t3_k2

获得

t1foo | t2foo | t3foo
t1bar | t2bar | t3bar
t1baz | t2baz | t3baz

现在我正在尝试使用bigQuery SQL获得相同的结果。根据我的理解,使用CROSS JOIN应该像常规SQL中的逗号一样工作,所以我认为以下内容可行:

SELECT t1_val, t2_val, t3_val
FROM test.t1 CROSS JOIN test.t2 CROSS JOIN test.t3
WHERE t1_k1 = t2_k1 AND t2_k2 = t3_k2

但是我收到一条错误,“在JOIN的任何一侧找不到”字段't3_k2'。 像这样添加括号:

SELECT SELECT t1_val, t2_val, t3_val
FROM ((test.t1 CROSS JOIN test.t2) CROSS JOIN test.t3)
WHERE t1_k1 = t2_k1 AND t2_k2 = t3_k2

在第0行第0列给出(坦率地说非常神秘)语法错误“遇到”“。 只有两个表CROSS JOIN可以工作,但它与普通的JOIN没什么不同。 我没有在两个以上的表中找到使用CROSS JOIN的示例。可能吗?我做错了吗?

3 个答案:

答案 0 :(得分:4)

尝试以下

SELECT t1_val, t2_val, t3_val 
FROM (
  SELECT t1_val, t2_val, t2_k2
  FROM test.t1 AS a 
  CROSS JOIN test.t2 AS b
  WHERE t1_k1 = t2_k1 
) AS c
CROSS JOIN test.t3 AS d
WHERE t2_k2 = t3_k2

注意:我认为您的示例仅适用于解决您的CROSS JOIN问题 - 但是想提一下,如果您的示例真正代表您的问题 - 您不需要CROSS JOIN - 而是需要[INNER] JOIN,如下所示

SELECT t1_val, t2_val, t3_val
FROM (
  SELECT t1_val, t2_val, t2_k2
  FROM test.t1 AS a JOIN test.t2 AS b
  ON t1_k1 = t2_k1 
) AS c
JOIN test.t3 AS d ON t2_k2 = t3_k2
  

为第二个查询添加了可运行的示例 - 证明它有效:o)

SELECT t1_val, t2_val, t3_val
FROM (
  SELECT t1_val, t2_val, t2_k2
  FROM (
    SELECT * FROM 
    (SELECT 1 AS t1_id, 'k1foo' AS t1_k1, 't1foo' AS t1_val),
    (SELECT 2 AS t1_id, 'k1bar' AS t1_k1, 't1bar' AS t1_val),
    (SELECT 3 AS t1_id, 'k1baz' AS t1_k1, 't1baz' AS t1_val)
  ) AS a 
  JOIN (
    SELECT * FROM 
    (SELECT 1 AS t2_id, 'k1foo' AS t2_k1, 'k2foo' AS t2_k2, 't2foo' AS t2_val),
    (SELECT 2 AS t2_id, 'k1bar' AS t2_k1, 'k2bar' AS t2_k2, 't2bar' AS t2_val),
    (SELECT 3 AS t2_id, 'k1baz' AS t2_k1, 'k2baz' AS t2_k2, 't2baz' AS t2_val)
  ) AS b
  ON t1_k1 = t2_k1 
) as c
JOIN (
  SELECT * FROM 
  (SELECT 1 AS t3_id, 'k2foo' AS t3_k2, 't3foo' AS t3_val),
  (SELECT 2 AS t3_id, 'k2bar' AS t3_k2, 't3bar' AS t3_val),
  (SELECT 3 AS t3_id, 'k2baz' AS t3_k2, 't3baz' AS t3_val)
) AS d
ON t2_k2 = t3_k2

答案 1 :(得分:0)

正如Mikhail在他的回答中注意到的,你不需要CROSS JOIN,常规JOIN工作正常。以下是如何在一个语句中执行此操作,没有多级JOIN:

我使用内联SELECT语句为t1,t2,t3提供数据:

SELECT t1_val, t2_val, t3.t3_val as t3_val
FROM (SELECT 1 as t1_id, "k1foo" as t1_k1, "t1foo" as t1_val) t1
JOIN (SELECT 1 as t2_id, "k1foo" as t2_k1, "k2foo" as t2_k2, "t2foo" as t2_val) t2
ON t1_k1 = t2_k1 
JOIN (SELECT 1 as t3_id, "k2foo" as t3_k2, "t3foo" as t3_val) t3
ON t2_k2 = t3_k2

答案 2 :(得分:0)

所以事实证明这是一个定义表别名的问题,请参阅另一个例子:CROSS JOIN: only two tables?