0

我在查询中使用了 group by 和 having 子句,并且使用别名似乎可以正常工作。无论我输入什么值,或者运算符 (<, >) 它都会返回正确的结果。根据逻辑查询处理,这应该不起作用,但它确实起作用。此外,即使我在有子句的 count 函数中放入了一些无意义的字符串,它仍然有效。

我完全感到困惑!

use TSQL2014;
select
c.categoryname,
count(p.productid) as 'TotalProducts'
from Production.Products p

left join Production.Categories c
on p.categoryid = c.categoryid

group by c.categoryname

--having count(p.productid) > 10 
having count('aaaaaa') > 10

order by 'TotalProducts' desc;
4

2 回答 2

2

为什么在having子句中使用别名有效?

'aaaaaa'不是别名而是字符串文字。

having count('aaaaaa') > 10
-- same as
       count(*)
       count(1) 
       count(GETDATE())

只要表达式不是 NULL,那么 COUNT 就会正常工作。

于 2019-06-17T15:43:13.770 回答
0

假设您指的是当前在您发布的代码中注释掉的行 -子句p中使用了别名from- 这意味着您可以在查询中的任何其他子句中使用它 - 包括子查询、具有子句,甚至应用子句和连接子句。

在子句中使用别名时,情况并非如此select——这些别名只能在order by子句中使用。

select
c.categoryname,
count(p.productid) as 'TotalProducts'
from Production.Products p

left join Production.Categories c

-- both `p` and `c` aliases are valid here since they where introduced in the `from` and `join` clauses
on p.categoryid = c.categoryid

-- the use of `c` here is valid since it was introduced in the `join` clause
group by c.categoryname

-- the use of `p` here is valid since `p` was introduced in the `from` clause.
having count(p.productid) > 10 

-- This, however, will cause an error - invalid column name `TotalProducts`
-- having count(TotalProducts) > 10 

-- This is valid since TotalProducts is an alias introduced in the `select` clause.
order by 'TotalProducts' desc;
于 2019-06-17T16:01:34.590 回答