[英]MySQL Order By multiple columns with Case End sort number as string
要按照以下順序進行選擇。
... ...
order by
case when t1.a is not null
then t1.a
else concat(t2.b, ',', t2.c)
end asc;
邏輯是如果t1.a為空,則按
t2.b asc, t2.c asc
t1.a,t2.b,t2.c均為INT或BIGINT。 問題是,t1.a被當作String排序,結果就像
10
100
1000
...
11
...
代替
10
11
12
...
100
...
主要是因為concat(...)返回一個String。 如何解決問題。
您的邏輯等效於此:
order by
case
when t1.a is not null
then t1.a
else t2.b
end,
t2.b,
t2.c
或者簡單地:
order by
coalesce(t1.a, t2.b),
t2.b,
t2.c
或這個:
order by
coalesce(t1.a, t2.b),
coalesce(t1.a, t2.c)
您可以使用LPAD()
進行零填充:
order by
case when t1.a is not null
then lpad(t1.a, 20, 0)
else concat(lpad(t2.b, 20, 0) , ',', lpad(t2.c, 20, 0) )
end asc
另一種方法是兩次使用CASE表達式:
order by
case when a is not null
then a
else b
end asc,
case when a is not null
then a
else c
end asc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.