使用帶有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中文網其他相關文章!