与 Go 和 PostgreSQL 不同的排序顺序

Different sort order from Go and PostgreSQL

SQL 查询排序文本数组

SELECT unnest(ARRAY['Go', '[Bravo]', 'Gopher', '[Alpha]', 'Grin', 'Delta']) ORDER BY 1 ASC;
 unnest  
---------
 [Alpha]
 [Bravo]
 Delta
 Go
 Gopher
 Grin

对字符串数组进行排序的 GO 代码 https://play.golang.org/p/UsWAKTz2Zj4

package main

import (
    "fmt"
    "sort"
)

func main() {
    s := []string{"Go", "[Bravo]", "Gopher", "[Alpha]", "Grin", "Delta"}
    sort.Strings(s)
    fmt.Println(s) // prints [Delta Go Gopher Grin [Alpha] [Bravo]]
}

为什么结果不同?

在你的SQL查询中你unnest数组。这似乎给出了没有或忽略 [].

的排序顺序

在go中,方括号被认为是字符串的一部分。这两个函数似乎都按字典顺序排序。

Go 似乎使用“ascii”排序。

您可以在 Postgres 中使用 collate "C" 实现:

SELECT word
from unnest(ARRAY['Go', '[Bravo]', 'Gopher', '[Alpha]', 'Grin', 'Delta']) as t(word) 
ORDER BY word collate "C" ;