问题
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