Want to sort Nulls and Blanks last and have read all the solutions that use either the Coalesce function or the If in the order by column.
MY problems is non of these work for me because the column I am sorting on is specified dynamically by the PHP script that creates the query and some of my columns are in two tables in my join.
$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";
This works great, I can change the variable $sortcol and my output listing works great except the nulls and blanks are at the top.
Based on other postings I tried this
$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";
This throws the error “column boat in ORDER BY clause is ambiguous”. Obviously it wants b.boat in the order by, but for reasons I won’t get into that is problematic.
It appears that anytime I try to use a function in the orderby clause I can’t use the column alias.
Any ideas for an elegant solution to this??
You’re right. For no reason that I can fathom, MySQL accepts an ambiguous
ORDER BYas long as the name you supply is not handled in any way (no way that I could think of. Maybe others exist).As soon as it is, ambiguousness gets rejected.
This is accepted (and redundant):
while
COALESCE(name, ''),name IS NULL,name OR NULLare all rejected.The obvious solution is to use a different name for the alias, one that does not appear in either table.
Another possibility would be to create a nested query:
That is: