组合左连接和 select 的语法错误

Syntax error to combine left join and select

我在 Left Join 中遇到语法错误。因此,在尝试将两者结合起来时,我使用了左连接和括号。我不确定问题出在哪里:

SELECT DISTINCT a.order_id
FROM fact.outbound AS a
ORDER BY Rand()
LIMIT 5
  LEFT JOIN (
    SELECT
      outbound.marketplace_name,
      outbound.product_type,
      outbound.mpid,
      outbound.order_id,
      outbound.sku,
      pbdh.mpid,
      pbdh.product_type,
      pbdh.validated_exp_reach,
      pbdh.ultimate_sales_rank_de,
      pbdh.ultimate_sales_rank_fr,
      (
        pbdh.very_good_stock_count + good_stock_count + new_Stock_count
      ) as total_stock
    FROM
      fact.outbound AS outbound
      LEFT JOIN reporting_layer.pricing_bi_data_historisation AS pbdh ON outbound.mpid = pbdh.mpid
      AND trunc(outbound.ordered_date) = trunc(pbdh.importdate)
    WHERE
      outbound.ordered_date > '2022-01-01'
      AND pbdh.importdate > '2022-01-01'
    LIMIT
      5
  ) AS b ON a.orderid = b.order_id

错误:

You have an error in your SQL syntax; it seems the error is around: 'LEFT JOIN ( SELECT outbound.marketplace_name, outbound.product_t' at line 9

可能是什么原因?

将第一个limit逻辑放到一个单独的子查询中,然后加入两个子查询:

SELECT DISTINCT a.order_id
FROM
(
    SELECT order_id
    FROM fact.outbound
    ORDER BY Rand()
    LIMIT 5
) a
LEFT JOIN
(
    SELECT
        outbound.marketplace_name,
        outbound.product_type,
        outbound.mpid,
        outbound.order_id,
        outbound.sku,
        pbdh.mpid,
        pbdh.product_type,
        pbdh.validated_exp_reach,
        pbdh.ultimate_sales_rank_de,
        pbdh.ultimate_sales_rank_fr,
        (pbdh.very_good_stock_count +
         good_stock_count + new_Stock_count) AS total_stock
    FROM fact.outbound AS outbound
    LEFT JOIN reporting_layer.pricing_bi_data_historisation AS pbdh
        ON outbound.mpid = pbdh.mpid AND
           TRUNC(outbound.ordered_date) = TRUNC(pbdh.importdate)
   WHERE outbound.ordered_date > '2022-01-01' AND
         pbdh.importdate > '2022-01-01'
   -- there should be an ORDER BY clause here...
   LIMIT 5
) AS b
    ON a.orderid = b.order_id;

请注意,b 子查询的 select 子句可以简化为 order_id,因为该子查询中没有值实际上 select结束。

您可以跳过 LEFT JOIN,因为没有选择 b 列。 (并且 SELECT DISTINCT 确保消除所有重复项。)

SELECT DISTINCT order_id
FROM fact.outbound
ORDER BY Rand()
LIMIT 5