Aliases not working in ORDER BY clause

▼魔方 西西 提交于 2019-12-25 03:28:17

问题


This will work fine in MySQL 5:

SELECT INSTR(foo, 'Bar') as foobar
FROM Table
ORDER BY CASE WHEN foobar = 1 THEN foo END DESC;

Bu in MySQL 4, I get the error:

ERROR 1054 (42S22): Unknown column 'foobar' in 'order clause'

However, if I change the clause to this, it will work on both versions:

SELECT INSTR(foo, 'Bar') as foobar
FROM Table
ORDER BY CASE WHEN INSTR(foo, 'Bar') = 1 THEN foo END DESC;

To ensure compatibility, do I have to always use the second way?


回答1:


because foobar is an alias. it is not a column unless it's from derived query (subquery).like thisone below

SELECT * 
FROM
(
   SELECT INSTR(foo, 'Bar') as foobar
   FROM Table
) a
ORDER BY CASE WHEN foobar = 1 THEN foo END DESC;



回答2:


Basically you cannot re-use a column alias at the same "query-level".

If you want to be write compatible/portable SQL and don't want to repeat the function call, then the usual way to do it, is to wrap the query into a derived table.

select *
from (
  SELECT INSTR(foo, 'Bar') as foobar,
         foo
  FROM Table
) t
ORDER BY CASE WHEN foobar = 1 THEN foo END DESC;

Note that you need to include any column you want to use in the "outer" query inside the inner query. If you omit the column foo in the inner derived table, you can not access it on the outer level.




回答3:


As per other answers, you can not use alias in CASE.
Instead of using sub-query you can direct use INSTR() in CASE like this:

SELECT INSTR(foo, 'Bar') as foobar
FROM Table
ORDER BY CASE WHEN INSTR(foo, 'Bar') = 1 THEN foo END DESC;

When you are using sub-query then note that you will also have to select foo column to order by it, other wise you will get an error like this

So your query with sub-query should be:

SELECT * FROM
(
    SELECT foo,INSTR(foo, 'Bar') as foobar
    FROM t
) A
ORDER BY CASE WHEN foobar = 1 THEN foo END DESC;


来源:https://stackoverflow.com/questions/13231167/aliases-not-working-in-order-by-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!