dougou8552 2019-08-18 19:05
浏览 9

如何使用联接查询从MySQL检索数据

I'm building a simple Go REST API with MySQL and I'm having some trouble querying the data when it comes to slightly more complicated queries. I have 2 models: books and genres. The model definitions in go are as below:

type Book struct {
    ID    string  `json:"id"`
    Title string  `json:"title"`
    Genre *Genre  `json:"genre"`
    Price float64 `json:"price"`
}


type Genre struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

In SQL, the book table has the fields id, title, price, and id_genre which is a foreign key.

The confusion is after performing the select which returns the rows, I'm not sure how to add the information to the Genre field when I'm looping through the rows

result, err := database.DB.Query("SELECT a.id_book, a.title, a.price, b.name, b.id_genre FROM bookshelf.books a JOIN bookshelf.genres b ON a.id_genre = b.id_genre")

for result.Next() {
    var book models.Book

    // ????
    err := result.Scan(&book.ID, &book.Title, &book.Price, &book.Genre )

    if err != nil {
        panic(err.Error())
    }
    // ...more code
}

Clearly in the result.Scan method is wrong, but I'm not sure how to go about the genre part.

Is this the right approach or am I approaching this all wrong?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
    • ¥15 unity连接Sqlserver
    • ¥15 图中这种约束条件lingo该怎么表示出来
    • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
    • ¥15 流式socket文件传输答疑
    • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
    • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
    • ¥15 win10,这种情况怎么办
    • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
    • ¥100 在连接内网VPN时,如何同时保持互联网连接