登录
首页 >  Golang >  Go问答

如何编写检查数组是否存在特定值的查询?

来源:stackoverflow

时间:2024-02-17 13:48:23 304浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《如何编写检查数组是否存在特定值的查询?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

这就是模型的外观:

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:“$1”处或附近的语法错误(sqlstate 42601)

请提出任何想法,任何选择。 p.s 使用 gorm、postgresql


正确答案


您可以在 where 子句中使用 in 运算符来检查值是否与值列表中的任何值匹配。

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: check if array field contains value?

gorm doc中有示例

db.where("name in ?", []string{"jinzhu", "jinzhu 2"}).find(&users)

今天关于《如何编写检查数组是否存在特定值的查询?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>