MySQL:How 将 Select 元素重写为 'y' 然后稍后在 where 语句中使用它

MySQL:How to Rewrite a Select element as 'y' then using that later in a where statement

所以我想做的是这个,但这不起作用:

Select count(staffno)as total_staff,avg(salary),branchno
From staff
Where total_staff > 1
Group by branchno

这是另一个例子:

Select salary,salary*1.015 as proposed_salary
From staff
Where proposed_salary > 50000

您不能在查询的 where 子句中使用聚合表达式(sum()count()、...)。 行由 group by 子句组合在一起之前评估此子句,因此聚合尚不可用。

在 SQL 中,这就是 having 子句的目的:

select count(staffno) as total_staff, avg(salary), branchno
from staff
having count(staffno) > 1 -- MySQL also allows "total_staff > 1"
group by branchno

至于第二个查询:select 子句中定义的别名在where 子句中也不可用(原因同上)。您可以重复表达式:

select salary, salary * 1.015 as proposed_salary
from staff
where salary * 1.015 > 50000

或者您可以使用派生的 table(cte 或子查询):

select *
from (
    select salary, salary * 1.015 as proposed_salary
    from staff
) t
where proposed_salary > 5000