Order by Column1 if Column1 is not null, otherwise order by Column2

点点圈 提交于 2020-08-02 06:15:10

问题


Is there a way to combine ORDER BY and IS NULL in sql so that I can order by a column if the column isn't null, but if it is null, order by another column?


回答1:


Something like:

ORDER BY CASE 
    WHEN Column1 IS NOT NULL THEN Column1
    ELSE Column2
END

Same as writing:

ORDER BY COALESCE(Column1, Column2)

Both should work in any sane RDBMS.




回答2:


Try this

  ORDER BY COALESCE(fieldA, fieldB);



回答3:


I dont have any Tables atm where I could test it, but this may work, at least it did without useable data:

SELECT * FROM table1
LEFT JOIN table2 ON table1.id = table2.id 
WHERE 1 
ORDER BY IF( table2.id, table1.id, table1.name )

Also I don't know how the order would look like if table2.id is null sometimes, seems very instable.




回答4:


You could try with the following:

ORDER BY ISNULL(firstField, secondField)


来源:https://stackoverflow.com/questions/11003413/order-by-column1-if-column1-is-not-null-otherwise-order-by-column2

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