简体   繁体   English

如何创建检查数组是否包含值的查询? 戈朗戈姆

[英]How to create query that checks if array contains value? golang gorm

This is how model looks:这是 model 的外观:

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"`
}

This is how contributors value looks in the postgresql column:这是 postgresql 列中贡献者值的样子:

图片

and how to make query that checks that contributors array contains for example 20?以及如何进行查询以检查贡献者数组是否包含例如 20? i tried to do like this: database.DB.Where("contributors IN?", 20).Find(&contBoards) but got error: ERROR: syntax error at or near "$1" (SQLSTATE 42601)我尝试这样做: database.DB.Where("contributors IN?", 20).Find(&contBoards)但出现错误: ERROR: syntax error at or near "$1" (SQLSTATE 42601)

Please any ideas, any options.请任何想法,任何选择。 PS using gorm, postgresql PS使用gorm,postgresql

You use IN operator in the WHERE clause to check if a value matches any value in a list of values.WHERE子句中使用IN运算符来检查值是否与值列表中的任何值匹配。

IN expects an explicit list of values (or a subquery). IN需要一个明确的值列表(或子查询)。

I have created a sample scenario for your case as follows:我为您的案例创建了一个示例场景,如下所示:

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, ",") + ")"

OR或者

ANY works with arrays. ANY适用于 arrays。 This can be useful if you have the list of values already in an array.如果数组中已有值列表,这将很有用。

With ANY operator you can search for only one value.使用ANY运算符,您只能搜索一个值。

select * from table_name where value = ANY(contributors);

If you want to search multiple values, you can use @> operator.如果要搜索多个值,可以使用@>运算符。

@> is the "contains" operator. @>是“包含”运算符。

Defined for several data types as follows:为几种数据类型定义如下:

arrays: http://www.postgresql.org/docs/current/static/functions-array.html arrays: http://www.postgresql.org/docs/current/static/functions-array.ZFC35FDC70D52C69D5236

range types: http://www.postgresql.org/docs/current/static/functions-range.html范围类型: http://www.postgresql.org/docs/current/static/functions-range.html

geometric types: http://www.postgresql.org/docs/current/static/functions-geometry.html几何类型: http://www.postgresql.org/docs/current/static/functions-geometry.html

JSON (and JSONB): http://www.postgresql.org/docs/current/static/functions-json.html JSON(和JSONB): http://www.postgresql.org/docs/current/static/functions-json.ZFC69A239EZ30D25

For better understanding you can refer this link: Postgres: check if array field contains value?为了更好地理解,您可以参考此链接: Postgres:检查数组字段是否包含值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM