我尝试使用这样的占位符进行查询
database.Query("select login,displayname from (select distinct $1+trunc(random()*$2)::integer as id from generate_series($3,$4) g ) r join users using(id) limit 10",min_id,max_id-min_id,min_id,max_id)
它给我一个错误:
pq: function generate_series(unknown, unknown) is not unique
然后我找到了一个将查询格式化为字符串的解决方案
query:=fmt.Sprintf("select login,displayname from (select distinct %v+trunc(random()*%v)::integer as id from generate_series(%v,%v) g ) r join users using(id) limit 10",min_id,max_id-min_id,min_id,max_id)
它有效。
我想让它以正确的方式工作,但我不明白为什么不这样做。
更新:
var min_id int64
var max_id int64
err:=_database.QueryRow("select min(id),max(id) from users").Scan(&min_id, &max_id)
if err!=nil {
log.Panicf("Failed to get min and max %v",err.Error())
return
}
var rows *sql.Rows
query:=fmt.Sprintf("select login,displayname from (select distinct %v+trunc(random()*%v)::integer as id from generate_series(%v,%v) g ) r join users using(id) limit 10",min_id,max_id-min_id,min_id,max_id)
log.Printf(query)
rows,err=_database.Query("select login,displayname from (select distinct $1+trunc(random()*$2)::integer as id from generate_series($3,$4) g ) r join users using(id) limit 10",min_id,max_id-min_id,min_id,max_id)
if err!=nil {
log.Panicf("failed to get random entries: %v",err)
}
慕侠2389804
相关分类