You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
在SQL常见面试题总结1中,计算总和这部分的sql语句
SELECT order_num, Sum(item_price * quantity) AS total_price
FROM OrderItems
GROUP BY order_num
HAVING total_price >= 1000
ORDER BY order_num
SQL语句中having的执行顺序是在select之前吧,所以having中不能写total_price吧
The text was updated successfully, but these errors were encountered:
我最近在一家公司实习,在熟悉项目的过程中,看到了很多这样的写法,一开始我也是真的蒙了,以前没讲过,因为我在学习的时候老师也是说的不要在 having 中以未聚合的字段作为条件过滤,后来查资料才发现可以提前在 select 中进行聚合,指定别名在 having 中使用。这两种写法有什么效率上的差别吗,有大佬可以解释一下吗
按照标准SQL规范来讲,一条SQL语句的执行顺序是这样的:
from
join
on
where
group by
having
select
distinct
order by
limit
根据这个标准having会在select之前执行,所以在having中使用select定义的别名会报错。
但是现在很多数据库都对此做了扩展,例如MySQL、SQLLite等都支持having使用聚合之后的别名。
因此具体使用时以数据库的种类和版本规范为准。
在SQL常见面试题总结1中,计算总和这部分的sql语句
SELECT order_num, Sum(item_price * quantity) AS total_price
FROM OrderItems
GROUP BY order_num
HAVING total_price >= 1000
ORDER BY order_num
SQL语句中having的执行顺序是在select之前吧,所以having中不能写total_price吧
The text was updated successfully, but these errors were encountered: