Using Go MySQL Queries with SET Variables
You're attempting to write a Go MySQL query that sets variables and uses them in a complex ORDER BY clause. The query runs successfully in the console but encounters a syntax error in Go.
Possible Solution
Unfortunately, Go's database/sql package currently does not support setting MySQL user-defined variables. Therefore, the approach described in the question is not feasible with the current limitations of the package.
Alternative Approaches
Dynamic Query Generation:
One alternative is to dynamically generate the ORDER BY clause based on the input parameters, eliminating the need for variable substitution.
<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>
Parameter Expansion:
Alternatively, you can manually expand the ? placeholders in the query string to avoid the need for variables. This approach involves building a string that replaces each ? with the corresponding parameter value.
<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>
The above is the detailed content of How to Use SET Variables in Go MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!