I'm studying databases with the book "Database System Concepts" from Silberschatz, Korth and Surdashan (I quote the authors because the relational algebra notation is different against other authors...
Well, I think that the execution order of a SQL query it's based in the relational algebra, for example:
If I have this SQL query:
SELECT nombre_sucursal, AVG(saldo) AS media_sucursal
FROM cuenta
GROUP BY nombre_sucursal
HAVING media_sucursal > 800
The corresponding relational algebra expression is the following:
Π nombre_sucursal (σ saldo > 800 (nombre_sucursal Ģ avg(saldo) (cuenta))
Well... For that, in my opinion, the execution order in a SQL query is (if you look at the relational algebra expression backwards):
I put the ??? symbols because this is the part that I don't understand:
If the SELECT clause is the last part of a SQL query, how can I rename the result of the aggregation function as "media_sucursal" and in the HAVING clause I'm able to use it?
I checked this question but it confirms what I put above, but not answer my question.
Any help is welcome!
Well it is the behavior of MySql extension to GROUP BY
MySQL Extensions to GROUP BY
MySQL extends this behavior to permit the use of an alias in the HAVING clause for the aggregated column
You can disable that extension with sql_mode
ONLY_FULL_GROUP_BY
SET [SESSION | GLOBAL] sql_mode = ONLY_FULL_GROUP_BY;
If you try to execute above-mentioned query in ONLY_FULL_GROUP_BY
sql_mode you'll get as the following error message:
Non-grouping field 'media_sucursal' is used in HAVING clause: SELECT nombre_sucursal, AVG(saldo) AS media_sucursal FROM cuenta GROUP BY nombre_sucursal HAVING media_sucursal > 800
as expected.
Here is SQLFiddle demo that illustrates that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.