gpt4 book ai didi

sql - 关于别名的 where 和 have 之间的区别

转载 作者:行者123 更新时间:2023-12-04 15:14:00 26 4
gpt4 key购买 nike

如果我在 select 中创建别名然后我不能在 where 中使用它子句因为按照sql查询的执行顺序where来之前 select .

但我可以在 select 中创建别名条款并在 having 中使用它条款虽然having来之前 select .

为什么会这样?

前任:

select type, (case when number>25 then 1 else 0 end) inc 
from animals
where inc='1';

这行不通。但,
select type, (case when number>25 then 1 else 0 end) inc 
from animals
having inc='1';

这有效。为什么这样?

最佳答案

基本上是因为它们是为不同的目的而定义的。 WHERE子句用于记录过滤和 HAVING子句设计用于过滤 聚合函数 ( GROUP BY )。
在您的第二个查询中,隐含 GROUP BY正在使用过滤,例如,如果您向 SELECT 添加另一列条款你最终会得到不同的结果。

编辑 基于 Martin Smith 的修正
HAVING创建是为了允许过滤由 GROUP BY 产生的行.当没有 GROUP BY被指定,整个结果被认为是一个组。

If neither a <where clause> nor a <group by clause> is specified, then let T be the result of the preceding <from clause>



或者

...the group is the entire table if no <group by clause> is specified



编辑 2
现在关于别名:

关于搜索条件中的列引用的 WHERE 子句的规范是这样说的:

Each <column reference> directly contained in the <search
condition>
shall unambiguously reference a column of T or be an outer reference.



引用:7.6 <where clause> , 语法规则 1。

关于搜索条件中的列引用的 HAVING 子句的规范是这样说的:

Each <column reference> directly contained in the <search
condition>
shall unambiguously reference a grouping column of T or be an outer reference.



引用:7.8 <having clause> , 语法规则 1。

还有一个 分组列定义为:

A column referenced in a <group by clause> is a grouping column.



所以总而言之 WHERE必须引用表的一列和 HAVING子句必须引用行组的分组列。

(Second Informal Review Draft) ISO/IEC 9075:1992, Database Language SQL- July 30, 1992

关于sql - 关于别名的 where 和 have 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12093405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com