最后排序Nulls

dav*_*ind 5 mysql null sql-order-by

想要最后对Nulls和Blanks进行排序,并阅读所有使用Coalesce函数或If by order by列的解决方案.

我的问题对我来说不起作用,因为我正在排序的列是由创建查询的PHP脚本动态指定的,而我的一些列在我的连接中的两个表中.

   $sortcol="boat";
   $sql= "SELECT fleet,b.boat as boat,owner FROM boats as b 
   LEFT JOIN owners as o ON  b.boat=o.boat 
   ORDER BY $sortcol";
Run Code Online (Sandbox Code Playgroud)

这很好用,我可以更改变量$ sortcol,我的输出列表工作得很好,除了空值和空格位于顶部.

基于其他帖子,我尝试了这个

   $sortcol="boat";
   $sql= "SELECT fleet,b.boat as boat,owner FROM boats as b 
   LEFT JOIN owners as o ON  b.boat=o.boat 
   ORDER BY IF($sortcol is NULL,1,0), $sortcol";
Run Code Online (Sandbox Code Playgroud)

这会引发错误"ORDER BY子句中的列船不明确".显然它需要b.boat按顺序,但由于我不会进入的原因是有问题的.看来,无论何时我尝试在orderby子句中使用函数,我都不能使用列别名.

任何想法优雅的解决方案?

LSe*_*rni 4

你说得对。出于我无法理解的原因,只要您提供的名称没有以任何方式处理(我想不到。也许还存在其他方式), MySQL就会接受歧义。ORDER BY

一旦出现,歧义就会被拒绝。

这是被接受的(并且是多余的):

select b.id, a.name as name
    FROM client AS a JOIN client AS b ON (a.id = b.id)
    ORDER BY name, name;
Run Code Online (Sandbox Code Playgroud)

COALESCE(name, '')name IS NULLname OR NULL均被拒绝。

显而易见的解决方案是为别名使用不同的名称,该名称不会出现在两个表中。

另一种可能性是创建嵌套查询:

SELECT * FROM ( your query here, without ORDER ) AS original
ORDER BY IF($sortcol is NULL,1,0), $sortcol;
Run Code Online (Sandbox Code Playgroud)

那是:

$sortcol="boat";
$sql = <<<SQL
   SELECT * FROM (
      SELECT fleet,b.boat as boat,owner FROM boats as b 
         LEFT JOIN owners as o ON  b.boat=o.boat 
   ) AS original
   ORDER BY IF($sortcol is NULL,1,0), $sortcol;
SQL;
Run Code Online (Sandbox Code Playgroud)