如何在 if 语句中按顺序使用列相对位置?
How can I use column relative position in if statement in order by?
我运行 SQL 查询如下 MySQL:
select *
from (
select 2 as o,1 as t from dual
union
select 1 as o,2 as t from dual
) x
order by if((select 1),o,t);
它运行良好,但是当我在 if
语句中使用列相对位置时,它不起作用。
如何在 ORDER BY
语句中使用 if
中的列相对位置?
select *
from (
select 2 as o,1 as t from dual
union
select 1 as o,2 as t from dual
) x
order by if((select 0),1,2);
我不确定你真正的困惑是什么。当整数出现在 order by
中时,这将被视为列号。整数的任何其他使用都被解释为表达式。
列号的使用已从 SQL 标准中删除。因此,在未来的版本中不保证它在任何特定数据库中的使用。使用列名确实更好。
我认为您想根据两列的条件对查询进行排序,如果我是正确的,您可以使用如下方式:
...
order by
case when (your criteria)
then column1
else column2
end;
注意:当您不想因为性能问题而删除重复值时,请使用 union all
而不是 union
;)。
我运行 SQL 查询如下 MySQL:
select *
from (
select 2 as o,1 as t from dual
union
select 1 as o,2 as t from dual
) x
order by if((select 1),o,t);
它运行良好,但是当我在 if
语句中使用列相对位置时,它不起作用。
如何在 ORDER BY
语句中使用 if
中的列相对位置?
select *
from (
select 2 as o,1 as t from dual
union
select 1 as o,2 as t from dual
) x
order by if((select 0),1,2);
我不确定你真正的困惑是什么。当整数出现在 order by
中时,这将被视为列号。整数的任何其他使用都被解释为表达式。
列号的使用已从 SQL 标准中删除。因此,在未来的版本中不保证它在任何特定数据库中的使用。使用列名确实更好。
我认为您想根据两列的条件对查询进行排序,如果我是正确的,您可以使用如下方式:
...
order by
case when (your criteria)
then column1
else column2
end;
注意:当您不想因为性能问题而删除重复值时,请使用 union all
而不是 union
;)。