JOIN using sqlx causes 'missing destination name'

huangapple go评论151阅读模式
英文:

JOIN using sqlx causes 'missing destination name'

问题

我有一个在MySQL上正常工作并返回预期结果的查询,但是sqlx在处理它时遇到了困难:

var jokes []model.Joke
err := shared.Dbmap.Select(&jokes, "SELECT * FROM joke INNER JOIN jokevote ON joke.id=jokevote.joke_id AND jokevote.vote=? AND joke.user_id=?", 1, userId)
if err != nil {
    log.Println(err)
}

在运行时,我没有得到任何结果,但终端上显示以下错误信息:

missing destination name joke_id

当查询单个表时,我没有这个问题。

所以我想知道这里出了什么问题,如何修复?

更新: 这是结构体:

type Joke struct {
    ID       int    `db:"id" json:"id"`
    UserID   int    `db:"user_id" json:"user_id"`
    Title    string `db:"title" json:"title"`
    Content  string `db:"content" json:"content"`
    ...
}

type JokeVote struct {
    ID     int `db:"id" json:"id"`
    JokeID int `db:"joke_id" json:"joke_id"`
    UserID int `db:"user_id" json:"user_id"`
    Vote   int `db:"vote" json:"vote"`
}
英文:

I have this query that works fine on mysql and return the intended result, but sqlx has difficulty to handle it:

var jokes []model.Joke
err := shared.Dbmap.Select(&jokes, "SELECT * FROM joke INNER JOIN jokevote ON joke.id=jokevote.joke_id AND jokevote.vote=? AND joke.user_id=?", 1, userId)
if err != nil {
	log.Println(err)
}

At runtime, I get no result but this error message in terminal:

> missing destination name joke_id

I don't have this issue when querying a single table.

So I'm wondering what is wrong here and how to fix it?

UPDATE: Here are the structs:

type Joke struct {
	ID         int       `db:"id" json:"id"`
	UserID     int       `db:"user_id" json:"user_id"`
	Title      string    `db:"title" json:"title"`
	Content    string    `db:"content" json:"content"`

...
}

type JokeVote struct {
	ID     int `db:"id" json:"id"`
	JokeID int `db:"joke_id" json:"joke_id"`
	UserID int `db:"user_id" json:"user_id"`
	Vote   int `db:"vote" json:"vote"`
}

答案1

得分: 3

当你执行"SELECT * FROM joke INNER JOIN jokevote"时,你将会得到来自joke和jokevote表的列。
尝试查询"SELECT joke.* FROM joke INNER JOIN jokevote",以仅获取来自joke表的列。

英文:

When you execute "SELECT * FROM joke INNER JOIN jokevote" you will get columns from both joke and jokevote tables.
Try to query "SELECT joke.* FROM joke INNER JOIN jokevote" to get only columns from joke table.

huangapple
  • 本文由 发表于 2017年7月20日 21:53:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/45216783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定