這是模型的外觀:
type Board struct {
Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
Owner uint `json:"owner"`
Name string `json:"name"`
Contributors datatypes.JSON `gorm:"type:jsonb" json:"contributors"`
GeneratedLink string `gorm:"default:''" json:"generated_link"`
Todos datatypes.JSON `gorm:"type:jsonb" json:"todos"`
}
這是 postgresql 列中的貢獻者值的外觀:

以及如何進行查詢以檢查貢獻者陣列是否包含例如 20?我試圖這樣做:database.DB.Where("contributors IN ?", 20).Find(&contBoards)
但出現錯誤:ERROR: syntax error at or near "$1" (SQLSTATE 42601)
請任何想法,任何選項。PS使用gorm,postgresql
uj5u.com熱心網友回復:
您可以IN在WHERE子句中使用運算子來檢查值是否與值串列中的任何值匹配。
IN 需要一個顯式的值串列(或子查詢)。
我為您的案例創建了一個示例場景,如下所示:
contributors := []int{20, 25, 27}
var tmp []string
for _, v := range contributors {
tmp = append(tmp, fmt.Sprint(v))
}
query := "SELECT * from table_name where contributors in (" strings.Join(tmp, ",") ")"
或者
ANY適用于陣列。如果陣列中已有值串列,這會很有用。
使用ANY運算子,您只能搜索一個值。
select * from table_name where value = ANY(contributors);
如果要搜索多個值,可以使用@>運算子。
@> 是“包含”運算子。
為幾種資料型別定義如下:
陣列:http : //www.postgresql.org/docs/current/static/functions-array.html
范圍型別:http : //www.postgresql.org/docs/current/static/functions-range.html
幾何型別:http : //www.postgresql.org/docs/current/static/functions-geometry.html
JSON(和 JSONB):http : //www.postgresql.org/docs/current/static/functions-json.html
為了更好地理解,您可以參考此鏈接:Postgres:檢查陣列欄位是否包含值?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380080.html
標籤:数组 数据库 PostgreSQL的 去 去吧
