即使你知道 order_qty 来自哪个表,因为你已经为你的两个表命名了 a 和 b,最好始终使用别名,以表达你的意思。
如果它们确实是字符串编码的布尔值,那么也有看起来像布尔值 inventory_stockout 和 flag_column 的东西是糟糕的性能。
DISTINCT 也是一个 GROUP BY,但如果你有 DISTINCT,你不需要声明 GROUP BY 阶段,因为所有变量都被考虑在内。同样作为雪花笔记,this_should_have_a_name 没有在 GROUP BY 中命名,但它也不需要,因为它是 GROUP BY 中的一组事物的派生值。
我假设您希望将结果集结合在一起,您可以像 littlefoot 所指出的那样 UNION 他们,但这将在两者之间运行,这是我假设您想要的。如果您知道两个结果集中有零个重复项,那么UNION ALL 会告诉数据库将结果连接在一起,这样会快得多。
接下来你可以做一个 CTE 和 sub 选择公共部分到一个块中,然后 UNION 子结果如下:
WITH cte AS (
SELECT DISTINCT
order_no,
status,
status_cd,
IFF( order_qty - fulfilled_qty > 0, 'inventory-unavailable', NULL) AS this_should_have_a_name,
a.subscription_enabled
FROM t1 AS a, t2 AS b
WHERE a.inventory_stockout = 'TRUE'
AND a.flag_column = 'TRUE'
)
SELECT order_no, status, status_cd, this_should_have_a_name
FROM cte
WHERE status in '(fulfilled','pending')
UNION
SELECT order_no, status, status_cd, this_should_have_a_name
FROM cte
WHERE subscription_enabled='TRUE'
;
现在我们看到它是这样写的,我们可以在 CTE 中放一个 OR
WITH cte AS (
SELECT DISTINCT
order_no,
status,
status_cd,
IFF( order_qty - fulfilled_qty > 0, 'inventory-unavailable', NULL) AS this_should_have_a_name,
a.subscription_enabled
FROM t1 AS a, t2 AS b
WHERE a.inventory_stockout = 'TRUE'
AND a.flag_column = 'TRUE'
)
SELECT order_no, status, status_cd, this_should_have_a_name
FROM cte
WHERE ( status in '(fulfilled','pending')
OR subscription_enabled='TRUE' )
;
或没有 CTE
SELECT DISTINCT
order_no,
status,
status_cd,
IFF( order_qty - fulfilled_qty > 0, 'inventory-unavailable', NULL) AS this_should_have_a_name
FROM t1 AS a, t2 AS b
WHERE a.inventory_stockout = 'TRUE'
AND a.flag_column = 'TRUE'
AND ( status in '(fulfilled','pending')
OR a.subscription_enabled='TRUE' )
;
OR 的速度可能会慢一些,现在逻辑被合并了,你可以将 UNION ALL 所需的逻辑视为
SELECT order_no, status, status_cd, this_should_have_a_name
FROM cte
WHERE status in '(fulfilled','pending')
AND subscription_enabled != 'TRUE'
UNION ALL
SELECT order_no, status, status_cd, this_should_have_a_name
FROM cte
WHERE subscription_enabled = 'TRUE'