1

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!

4

1 回答 1

2

那么这是MySql扩展的行为GROUP BY

MySQL Extensions to GROUP BY
MySQL 扩展此行为以允许在 HAVING 子句中为聚合列使用别名

您可以使用禁用该扩展程序sql_mode ONLY_FULL_GROUP_BY

SET [SESSION | GLOBAL] sql_mode = ONLY_FULL_GROUP_BY;

如果您尝试在 sql_mode 中执行上述查询,ONLY_FULL_GROUP_BY您将收到以下错误消息:

非分组字段“media_sucursal”用于 HAVING 子句:SELECT nombre_sucursal, AVG(saldo) AS media_sucursal FROM cuenta GROUP BY nombre_sucursal HAVING media_sucursal > 800

正如预期的那样。

这是说明这一点的SQLFiddle演示。

于 2013-08-11T06:30:19.007 回答