用于将布尔列排序为 true、null、false 的 SQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2828120/
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
SQL for sorting boolean column as true, null, false
提问by petehern
My table has three boolean fields: f1, f2, f3. If I do
我的表有三个布尔字段:f1、f2、f3。如果我做
SELECT * FROM table ORDER BY f1, f2, f3
the records will be sorted by these fields in the order false, true, null. I wish to order them with null in between true and false: the correct order should be true, null, false.
记录将按这些字段按 false、true、null 的顺序排序。我希望在 true 和 false 之间用 null 对它们进行排序:正确的顺序应该是 true、null、false。
I am using PostgreSQL.
我正在使用 PostgreSQL。
回答by meriton
Not beautiful, but should work:
不漂亮,但应该有效:
... order by (case when f1 then 1 when f1 is null then 2 else 3 end) asc
回答by Yo Ludke
A better solution would be to use
更好的解决方案是使用
f1 DESC NULLS LAST
f1 DESC NULLS LAST
if you're okay with the order true, false, nil ( I guess the important part of your question was, like in my situation now, to have the not-true vaules together)
如果您对 true、false、nil 的顺序没有意见(我想您的问题的重要部分是,就像我现在的情况一样,将不真实的值放在一起)
回答by jc david
you could do also as follows:
你也可以这样做:
order by coalesce(f1, FALSE), coalesce(f1, TRUE), ...
If f1
is TRUE
, you get: TRUE, TRUE
If f1
is NULL
, you get: FALSE, TRUE
If f1
is FALSE
, you get: FALSE, FALSE
如果f1
是TRUE
,你得到:TRUE, TRUE
如果f1
是NULL
,你得到:FALSE, TRUE
如果f1
是FALSE
,你得到:FALSE, FALSE
which corresponds to the sorting order you want.
这对应于您想要的排序顺序。
回答by FireLeopard
It is also possible to do as follows:
也可以执行以下操作:
... ORDER BY (CASE WHEN f1 IS NOT NULL THEN f1::int * 2 ELSE 1 END) DESC