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 :)

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

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本