登录
首页 >  Golang >  Go问答

gorm 有 OR 查询

来源:stackoverflow

时间:2024-03-29 22:36:31 101浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《gorm 有 OR 查询》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

我陷入了生成在运行时动态创建的查询的困境。

我想创建一个 having 查询,中间有 or,例如

select name from `user_group`  where ((group_key = 'age' and group_value = '20')) 

or ((group_key = 'division' and group_value = 'accounting')) 
or ((group_key = 'age' and group_value = '22')) 
or ((group_key = 'division' and group_value = 'kitchen'))

group_by name
having 
((sum(group_key = 'age' and group_value = '20') > 0) 
and 
(sum(group_key = 'division' and group_value = 'accounting') > 0))

or 

((sum(group_key = 'age' and group_value = '22') > 0) 
and 
(sum(group_key = 'division' and group_value = 'kitchen') > 0))

请注意,having 语句中的 or 就是我所要求的。

我目前通过 gorm 得到了这个:

select name from `user_group`  where ((group_key = 'age' and group_value = '20')) 

or ((group_key = 'division' and group_value = 'accounting')) 
or ((group_key = 'age' and group_value = '22')) 
or ((group_key = 'division' and group_value = 'kitchen'))

group_by name
having 
((sum(group_key = 'age' and group_value = '20') > 0) 
and 
(sum(group_key = 'division' and group_value = 'accounting') > 0))

and 

((sum(group_key = 'age' and group_value = '22') > 0) 
and 
(sum(group_key = 'division' and group_value = 'kitchen') > 0))

注意 having 语句中的 and

这是查询生成:

for _, condition := range resp.Allow.Conditions {
    for key, val := range condition {
        if len(key) <= 0 || len(val) <= 0 {
            continue
        }
        groupQuery = groupQuery.Or("(group_key = ? AND group_value = ?)", key, val)
        groupQuery = groupQuery.Having("SUM(group_key = ? AND group_value = ?) > 0", key, val)
    }
}
groupQuery = groupQuery.Group('name')

gorm 中有什么方法可以做到这一点吗?我查看了文档,我最好的选择是它必须是原始 sql 查询。我不喜欢它,但如果这是唯一的方法也没关系。

注意:我使用 mysql 作为方言


解决方案


该行的输出:

groupquery = groupquery.having("sum(group_key = ? and group_value = ?) > 0", key, val)

是块

((sum(group_key = 'age' and group_value = '20') > 0) 
and 
(sum(group_key = 'division' and group_value = 'accounting') > 0))

and 

((sum(group_key = 'age' and group_value = '22') > 0) 
and 
(sum(group_key = 'division' and group_value = 'kitchen') > 0))

这是正确的。查看每行的所有左括号和右括号:

````(cond1)和(cond2)和(cond3)和(cond4)````

要根据您的要求在having语句的中间获取一个或:

((sum(group_key = 'age' and group_value = '20') > 0) 
and 
(sum(group_key = 'division' and group_value = 'accounting') > 0))

and 

((sum(group_key = 'age' and group_value = '22') > 0) 
and 
(sum(group_key = 'division' and group_value = 'kitchen') > 0))

这将是:

(cond1) 与 (cond2) 或 (cond3) 与 cond(4)

会导致不太预期的结果。

更合乎逻辑的是:

(cond1) 或 (cond2) 或 (cond3) 或 cond(4)

或者:

((cond1)和(cond2))或((cond3)和cond(4))

最后一个版本(似乎是您的目标)无法按照规定在循环中生成,并且需要特定的方法。

看起来您几乎只能使用原始 sql。

到这里,我们也就讲完了《gorm 有 OR 查询》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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