我在GO中有一个查询,它从mysql返回一个不同的响应。
这是查询:
SELECT DISTINCT
questions.id as question_id,
questions.question,
questions.priority,
questions.type
FROM questions
LEFT JOIN profile ON profile.user_id = ?
LEFT JOIN group ON group.user_id = profile.user_id
WHERE questions.status = 1
AND group.status = 1
AND questions.id NOT IN (SELECT DISTINCT question_id FROM answers WHERE user_id = profiles.user_id)
当我在mysql终端上运行它时,它没有按预期返回任何内容。但是当我尝试在GO语言上运行它时,它有一个不应该被返回的返回,因为它已经在NOT IN子句中被过滤,这是所有已回答的问题。当我尝试将profiles.user_id更改为特定值时,它返回预期的输出。
我认为使用列参数不能在GO中工作。如果我将users.profile更改为特定变量,但是有其他查询需要使用该功能才能实现我的预期输出,这将是一个快速解决方案。
我尝试使用stmt.Prepared语句和db.Query()具有相同的结果
转到代码:
query := " SELECT DISTINCT " +
" questions.id as question_id, " +
" questions.question, " +
" questions.priority, " +
" questions.type " +
" FROM questions " +
" LEFT JOIN profile ON profile.user_id = 1627 " +
" LEFT JOIN group ON group.user_id = profile.user_id " +
" WHERE questions.status = 1 " +
" AND group.status = 1 " +
" AND questions.id NOT IN (SELECT DISTINCT question_id FROM answers WHERE user_id = profiles.user_id); "
stmt, err := db.Prepare(query)
if err != nil {
checkErr(err) // proper error handling instead of panic in your app
}
defer stmt.Close() // Close the statement when we leave main() / the program terminates
userId := json.userId
args := []interface{}{}
args = append(args, userId)
start := time.Now()
rows, err := stmt.Query(args...)
elapsed := time.Since(start)
if err != nil {
checkErr(err) // proper error handling instead of panic in your app
}
// Fetch rows
for rows.Next() {
// get RawBytes from data
err = rows.Scan(&question.QuestionId, &question.Question, &question.Priority, &question.Type)
questions = append(questions, question)
if err != nil {
checkErr(err) // proper error handling instead of panic in your app
}
}
defer rows.Close()
defer db.Close()
有没有可行的解决方法?
感谢您的回复
答案 0 :(得分:0)
您可以使用问号'?'在您期望参数的地方的查询中:
age := 27
rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Printf("%s is %d\n", name, age)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
此外,你可以在代码中使用back tick来表示多行字符串(而不是用+连接)。这将使您的代码更容易阅读。
query := `SELECT DISTINCT
questions.id as question_id,
questions.question,
questions.priority,
questions.type
FROM questions
LEFT JOIN profile ON profile.user_id = 1627
LEFT JOIN group ON group.user_id = profile.user_id
WHERE questions.status = 1
AND group.status = 1
AND questions.id NOT IN (SELECT DISTINCT question_id FROM answers WHERE user_id = profiles.user_id); `