【问题标题】:use multiple LEFT JOINs from multiple datasets SQL使用来自多个数据集 SQL 的多个 LEFT JOIN
【发布时间】:2020-06-25 20:30:46
【问题描述】:

我需要执行多个 JOIN,我正在从多个表中获取数据并在 id 上进行 JOIN。棘手的部分是一张桌子我需要加入两次。代码如下:

(
    SELECT
        content.brand_identifier AS brand_name,
        CAST(timestamp(furniture.date) AS DATE) AS order_date,
total_hearst_commission
    FROM
        `furniture_table` AS furniture
        LEFT JOIN `content_table` AS content ON furniture.site_content_id = content.site_content_id
    WHERE
        (
            timestamp(furniture.date) >= TIMESTAMP('2020-06-01 00:00:00')
        )
)
UNION
(
    SELECT
        flowers.a_merchant_name AS merchant_name
    FROM
        `flowers_table` AS flowers
        LEFT JOIN `content` AS content ON flowers.site_content_id = content.site_content_id
)
GROUP BY
    1,
    2,
    3,
    4
ORDER BY
    4 DESC
LIMIT
    500

我以为我可以使用 UNION,但它给了我一个错误 Syntax error: Expected keyword ALL or keyword DISTINCT but got "("

【问题讨论】:

  • 此查询有多个错误。首先,两个子查询返回的列数不同。样本数据和期望的结果将有助于阐明您想要什么。
  • SELECT ... UNION SELECT ... 即跳过那些括号。
  • 让它变得简单,并有可能为您提供帮助:minimal reproducible example
  • 这是最小的可重现示例。我不知道还有什么方法可以最小化它。整个代码是我需要解决的,这就是我在这里发布的原因。
  • 虽然语法不正确,group by 的预期用途是什么?按所有列分组是没有意义的。无论如何,第一个结果只有三列(少于 4 列)。

标签: sql google-bigquery left-join union


【解决方案1】:

我无法发表评论,但与 GHB 状态一样,查询的列数不同;因此,UNION 在这里不起作用。

我认为首先了解为什么需要子查询会很有帮助。我猜这个查询不会产生你想要的结果,所以请详细说明为什么会这样。

    select 
        f.a_merchant_name as merchant_name,
        c.brand_identifier as brand_name, 
        CAST(timestamp(f.date) AS DATE) AS order_date,
        total_hearst_commission
    from furniture_table f
    left join content_table c on c.site_content_id = f.site_content_id
    where timestamp(f.date) >= TIMESTAMP('2020-06-01 00:00:00')
    group by 1,2,3,4

【讨论】:

    猜你喜欢
    • 2017-02-20
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多