Вопрос

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):

  1. FROM - (cuenta) the base relation in the relational algebra expression
  2. GROUP BY nombre_sucursal - nombre_sucursal Ģ avg(saldo) in the relational algebra expression
  3. HAVING media_sucursal > 800 - σ saldo > 800 the selection operation in the relational algebra expression
  4. SELECT nombre_sucursal, AVG(saldo) AS media_sucursal - Π nombre_sucursal ???

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top