postgresql 如果 Column1 不为空,则按 Column1 排序,否则按 Column2 排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11003413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Order by Column1 if Column1 is not null, otherwise order by Column2
提问by 1252748
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?
有没有办法在 sql 中组合ORDER BY
和IS NULL
以便我可以在列不为空时按列排序,但如果为空,则按另一列排序?
回答by Salman A
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.
两者都应该在任何正常的 RDBMS 中工作。
回答by vearutop
Try this
试试这个
ORDER BY COALESCE(fieldA, fieldB);
回答by Nurickan
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.
另外我不知道如果 table2.id 有时为空,订单会是什么样子,看起来很不稳定。
回答by crassr3cords
You could try with the following:
您可以尝试以下操作:
ORDER BY ISNULL(firstField, secondField)