gorm用OR查询

时间:2018-10-23 22:30:49

标签: go go-gorm

我被困在生成一个在运行时动态创建的查询。

我想创建一个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))

请注意,OR内的having是我要问的。

我目前在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))

请注意AND语句中的having

这是查询生成:

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作为方言

1 个答案:

答案 0 :(得分:0)

该行的输出:

    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)AND(COND2)AND(COND3)AND(COND4)`''

根据您的要求获得单条或在Haven语句中间:

((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) AND (COND2) OR (COND3) AND COND(4)

将导致预期结果较差。

更合乎逻辑的是:

(COND1) OR (COND2) OR (COND3) OR COND(4)

或者:

((COND1) AND (COND2)) OR ((COND3) AND COND(4))

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

看来您已经沦为原始SQL了。