简体   繁体   English

别名在ORDER BY子句中不起作用

[英]Aliases not working in ORDER BY clause

This will work fine in MySQL 5: 这将在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: 在MySQL 4中,Bu出现错误:

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? 为了确保兼容性,我是否必须始终使用第二种方法?

because foobar is an alias. 因为foobar是别名。 it is not a column unless it's from derived query ( subquery ).like thisone below 除非它来自派生查询( subquery ),否则它不是列。

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

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. 如果您想编写兼容/便携式的SQL,并且不想重复该函数调用,那么通常的做法是将查询包装到派生表中。

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. 如果在内部派生表中省略了列foo ,则无法在外部级别上对其进行访问。

As per other answers, you can not use alias in CASE . 根据其他答案,您不能在CASE使用别名。
Instead of using sub-query you can direct use INSTR() in CASE like this: 代替使用子查询,您可以像这样直接在CASE使用INSTR()

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 当您使用子查询时,请注意,您还必须选择foo列对其进行排序,否则,您将得到类似的错误

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM