带大括号的 SQL 运算符优先级
Posted
技术标签:
【中文标题】带大括号的 SQL 运算符优先级【英文标题】:SQL Operator Precedence with braces 【发布时间】:2018-09-29 05:41:59 【问题描述】:我有一个关于运算符优先级的 SQL 查询我不太了解:
SELECT
foo,
count(*)
FROM
A
JOIN (SELECT
SUM(IF(bar = 2,1,0)) as bar_sum,
SUM(IF(foo >= 1,1,0)) as foo,
SUM(1) as sum_1
FROM
B
) as sums
GROUP BY
id,
bar_sum,
foo,
sum_1
ON A.id = B.id
外大括号中的GROUP BY
真的适用于内大括号吗?
请注意,我需要将此 SQL 从 Hive 移植到 Spark scala Dataframe API,因此我确实需要正确设置运算符优先级。从What is the execution sequence of Group By, Having and Where clause in SQL Server? 看来,这通常是正确的,但我没有找到任何关于()
的文档。
【问题讨论】:
【参考方案1】:此查询看起来不正确(缺少ON
子句)
SELECT foo,count(*)
FROM A
JOIN (SELECT SUM(IF(bar = 2,1,0)) as bar_sum,
SUM(IF(foo >= 1,1,0)) as foo,
SUM(1) as sum_1
FROM B) as sums -- should be `ON`
GROUP BY id, bar_sum, foo, sum_1;
-- looks like grouping by sum_1, bar_sum is superflous
GROUP BY
仅适用于外部查询。请注意,内部查询将返回单行。
SELECT SUM(IF(bar = 2,1,0)) as bar_sum,
SUM(IF(foo >= 1,1,0)) as foo,
SUM(1) as sum_1
FROM B
-- single row
然后将单行连接到表 A 并获得与不同 (id,foo) 值一样多的行。
【讨论】:
以上是关于带大括号的 SQL 运算符优先级的主要内容,如果未能解决你的问题,请参考以下文章