Bug #5866 | Inconsistent column 'ambiguousness' | ||
---|---|---|---|
Submitted: | 3 Oct 2004 10:36 | Modified: | 9 Oct 2004 10:09 |
Reporter: | Olaf van der Spek (Basic Quality Contributor) | Email Updates: | |
Status: | Not a Bug | Impact on me: | |
Category: | MySQL Server | Severity: | S4 (Feature request) |
Version: | MySQL 4.0.21-nt | OS: | Windows (Windows XP) |
Assigned to: | CPU Architecture: | Any |
[3 Oct 2004 10:36]
Olaf van der Spek
[3 Oct 2004 13:51]
Alexander Keremidarski
MySQL behaves consistency, but it is a bit obscure. In ORDER BY clause it is allowed to use * column name e.g. SELECT ... ORDER BY tb.a * alias e.g. SELECT tb.a AS x ... ORDER BY x * expression or function possibly depending on columns The problem you observe is due to fact that expression in ORDER BY can not contain aliases. SELECT tb.a AS x FROM tb ORDER BY x; --> correct SELECT tb.a AS x FROM tb ORDER BY (x + 0); --> wrong In your example select tb.*, tb.a a, tb.b b from ta inner join tb order by a + b; (a + b) in ORDER BY can *not* use aliases you have set in SELECT part. It is only allowed to use column names from tables. In your case both tables have columns called a and this is what causes the error. You can observe this error with: mysql> select 1 from ta, tb order by a; ERROR 1052 (23000): Column 'a' in order clause is ambiguous As for the first query it succeeds because there is no ambiguity in select part. select tb.*, tb.a a, tb.b b from ta inner join tb order by a; Here result column names are (a, b, a, b) but alias `a` is an alias of the column `a` so it doesn't matter which one will be used for sorting. Try to add another alias `a` and the same error will occur again Let's simplify the example: select ta.a, ta.a as a from ta order by a; -- this is OK mysql> select ta.a, ta.b as a from ta order by a; -- this is wrong ERROR 1052 (23000): Column 'a' in order clause is ambiguous
[3 Oct 2004 13:53]
Olaf van der Spek
Why are functions in ORDER BY not allowed to depend on aliases?
[3 Oct 2004 14:07]
Olaf van der Spek
And does this mean MySQL evaluates this expression twice? What if it's a fairly expensive expression?
[3 Oct 2004 14:09]
Olaf van der Spek
Hmm, even worse, what if you want to order by a group function?
[5 Oct 2004 8:43]
Olaf van der Spek
Could you reopen this as feature request?
[9 Oct 2004 10:09]
Konstantin Osipov
MySQL does not evaluate aggregate functions twice. Your note about double evaluation of expressions, if they're used in ORDER BY seems to be valid. Note, that the same thing happens if you use an expression twice in SELECT list: SELECT expensive_func(a), expensive_func(a)+1 from t; -- expensive_func will be evaluated twice. You can't use aliases to solve the problem here as well: SELECT expensive_func(a) as ef, ef+1 from t; -- this won't parse
[21 Sep 2005 8:14]
Olaf van der Spek
Could you reopen this as feature request?