首页  >  文章  >  后端开发  >  如何在 Go MySQL 查询中使用 SET 变量?

如何在 Go MySQL 查询中使用 SET 变量?

Patricia Arquette
Patricia Arquette原创
2024-10-23 17:49:02396浏览

How to Use SET Variables in Go MySQL Queries?

使用带有 SET 变量的 Go MySQL 查询

您正在尝试编写一个 Go MySQL 查询来设置变量并在复杂的环境中使用它们ORDER BY 子句。查询在控制台中成功运行,但在 Go 中遇到语法错误。

可能的解决方案

不幸的是,Go 的数据库/sql 包目前不支持设置 MySQL 用户-定义的变量。因此,问题中描述的方法在包的当前限制下不可行。

替代方法

动态查询生成:

一种替代方案是根据输入参数动态生成 ORDER BY 子句,从而无需进行变量替换。

<code class="go">func (d *DB) SelectByUserId(uid string, srt string, pg, lim int) ([]Inventory, error) {
    query := `
    SELECT
        *
    FROM
        inventory
    WHERE
        user_id = ?
    ORDER BY
        ` + generateOrderBy(srt) + `
    LIMIT ?,?;
    `

    rows, err := d.Query(
        query,
        uid,
        pg*lim,
        lim,
    )

    // ... (rest of the code remains the same)

    return result, nil
}

func generateOrderBy(srt string) string {
    order := ""
    switch srt {
    case "type,asc":
        order = "`type` ASC"
    case "type,desc":
        order = "`type` DESC"
    // ... (add other cases)
    }
    return order
}</code>

参数扩展:

或者,您可以手动扩展 ?查询字符串中的占位符以避免需要变量。这种方法涉及构建一个字符串来替换每个 ?与相应的参数值。

<code class="go">func (d *DB) SelectByUserId(uid string, srt string, pg, lim int) ([]Inventory, error) {
    query := fmt.Sprintf(`
    SELECT
        *
    FROM
        inventory
    WHERE
        user_id = '%s'
    ORDER BY
        CASE WHEN '%s' = 'type,asc' THEN `type` END,
        CASE WHEN '%s' = 'type,desc' THEN `type` END DESC,
        CASE WHEN '%s' = 'visible,asc' THEN visible END,
        CASE WHEN '%s' = 'visible,desc' THEN visible END DESC,
        CASE WHEN '%s' = 'create_date,asc' THEN create_date END,
        CASE WHEN '%s' = 'create_date,desc' THEN create_date END DESC,
        CASE WHEN '%s' = 'update_date,asc' THEN update_date END,
        CASE WHEN '%s' = 'update_date,desc' THEN update_date END DESC
    LIMIT %d,%d;
    `, uid, srt, srt, srt, srt, srt, srt, srt, srt, pg*lim, lim)

    rows, err := d.Query(
        query,
    )

    // ... (rest of the code remains the same)

    return result, nil
}</code>

以上是如何在 Go MySQL 查询中使用 SET 变量?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn