我试图通过设置一些变量来清理 Go 调用 MySQL 查询的方式,然后再使用围绕单个值的大量 case 语句运行查询。我尝试运行的查询在控制台上运行良好,但在SELECT通过 Go 运行它时因语法问题而失败。这样的事情可能吗?
func (d *DB) SelectByUserId(uid string, srt string, pg, lim int) ([]Inventory, error) {
query := `
SET @user_id := ?,
@orderBy := ?;
SELECT
*
FROM
inventory
WHERE
user_id = @user_id
ORDER BY
(CASE WHEN @orderBy = 'type,asc' THEN type END),
(CASE WHEN @orderBy = 'type,desc' THEN type END) DESC,
(CASE WHEN @orderBy = 'visible,asc' THEN visible END),
(CASE WHEN @orderBy = 'visible,desc' THEN visible END) DESC,
(CASE WHEN @orderBy = 'create_date,asc' THEN create_date END),
(CASE WHEN @orderBy = 'create_date,desc' THEN create_date END) DESC,
(CASE WHEN @orderBy = 'update_date,asc' THEN update_date END),
(CASE WHEN @orderBy = 'update_date,desc' THEN update_date END) DESC
LIMIT ?,?;
`
rows, err := d.Query(
query,
uid,
srt,
pg*lim,
lim,
)
if err != nil {
return nil, err
}
defer rows.Close()
result := make([]Inventory, 0)
for rows.Next() {
var inv Inventory
if err := rows.Scan(
&inv.Id,
&inv.UserId,
&inv.Type,
&inv.Name,
&inv.Description,
&inv.Visible,
&inv.CreateDate,
&inv.UpdateDate); err != nil {
return result, err
}
result = append(result, inv)
}
if err = rows.Err(); err != nil {
return result, err
}
return result, nil
}
现在,如果我取出 SET 部分并将所有@变量替换为?,然后srt像下面这样多次传递变量,这一切都有效。但真的不想有查询调用,例如:
rows, err := d.Query(
query,
uid,
srt,
srt,
srt,
srt,
srt,
srt,
srt,
srt,
pg*lim,
lim)
PIPIONE
慕丝7291255
德玛西亚99
相关分类