doubomudichen0832 2018-08-24 15:06
浏览 20
已采纳

在选择中使用子查询

Is there any way to use the SubQuery function in Select?? I have seen it as part of Where clause, but I need on select.

I am solving this temporary doing this:

func GetUserProviders(userID int) ([]userprovider, error) {
    providers := []userprovider{}
    query := `SELECT (count(users_providers.user_id) > 0) 
                FROM users_providers 
                WHERE users_providers.user_id = '` + strconv.Itoa(userID) + `' AND users_providers.provider_id=providers.id`
    rows, err := db.DB.Table("providers").
        Select("providers.id, providers.name, (" + query + ") as checked").Rows()

    if err == nil {
        for rows.Next() {
            var provider = userprovider{}
            db.DB.ScanRows(rows, &provider)
            providers = append(providers, provider)
        }
    }
    return providers, err
}

But I would prefer, if possible, to use the function of the ORM instead concatenating strings.

In this case there is no danger, but for other cases, it would be great if there was any function to tranform

// SQL expression
type expr struct {
    expr string
    args []interface{}
}

into a sanitized String.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dtdt0454 2018-08-24 16:11
    关注

    Ok... I found the solution:

    q := db.DB.Table("users_providers").
        Select("(count(users_providers.user_id) > 0)").
        Where("users_providers.user_id = ? AND users_providers.provider_id=providers.id", userID).
        SubQuery()
    rows, err := db.DB.Table("providers").
        Select("providers.id, providers.name, ? as checked", q).
        Rows()
    

    The Select function accepts 2 arguments: one for the query and the other one for the args, working in the same way than the Where.

    Thanks any way :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据