猿问

左连接如何与 sqlx 一起工作

我正在尝试内部连接两个表person并profile使用一个简单的查询,该查询似乎适用于 mysql 但不适用于 sqlx。这是我的代码:


package main 


import (

    "fmt"

    "github.com/jmoiron/sqlx"

    _ "github.com/go-sql-driver/mysql"

)


type Person struct {

    Id      int64   `db:"id"`

    Name    string  `db:"name"`

    Email   string  `db:"email"`

}


type Profile struct {

    Id          int64   `db:"id"`

    Face        string  `db:"face"`

    Hair        string  `db:"hair"`

    Person

}


func main() {

    DB, err := sqlx.Connect("mysql", "root:hackinitiator@/dusk")

    if err == nil {

        fmt.Println("sucess!!")

    } 

    var q []Profile

    DB.Select(&q, "select person.id, person.name, person.email, profile.id, profile.face, profile.hair from profile left join person on person.id = profile.person_id")

    fmt.Println(q)

}

mysql 查询产生以下输出:


+------+------+---------+----+----------+--------+

| id   | name | email   | id | face     | hair   |

+------+------+---------+----+----------+--------+

|    1 | yoda | nomail  |  1 | round    | brown  |

|    5 | han  | nomail1 |  3 | circle   | red    |

|    6 | yun  | nomail2 |  4 | triangle | yellow |

|    7 | chi  | nomail3 |  5 | square   | green  |

+------+------+---------+----+----------+--------+

这很好,但我的 go 程序没有按预期响应。该结构无法捕获配置文件 ID(输出中为空),并且人员 ID 已替换为配置文件 ID。下面是输出(格式化):


[

{0 round brown {1 yoda nomail}} 

{0 circle red {3 han nomail1}} 

{0 triangle yellow {4 yun nomail2}} 

{0 square green {5 chi nomail3}}

]

我无法弄清楚出了什么问题。


鸿蒙传说
浏览 121回答 3
3回答

繁星点点滴滴

我做了一些更改,使我可以无错误地运行程序,并且无需重命名 db 标签。首先,我在配置文件结构中添加了以下代码,让查询识别人员结构Person `db:"person"`在此之后,我将 SQL 查询字符串更改为以下代码DB.Select(&q, `select person.id "person.id", person.name "person.name", person.email "person.email", profile.* from profile left join person on person.id = profile.person_id`)

阿晨1998

该错误是由于id从结果中返回两列但将结果存储在两个结构中具有相同字段名称 id 的结构中,您将其实例传递给 DB.Select。尝试捕获单个 id 列并将其传递给结构。传递多个列但不同的列名,您可以将其用作别名。列别名将是您在其中扫描数据的 Person 结构中的字段:type Person struct {    PersonId    int64   `db:"personId"`    Name        string  `db:"name"`    Email       string  `db:"email"`}var q []ProfileDB.Select(&q, "select person.id as personId, person.name, person.email, profile.id, profile.face, profile.hair from profile left join person on person.id = profile.person_id")fmt.Println(q)

UYOU

您需要像下面我描述的那样更改结构db中的名称person,因为会有两列具有相同的名称,id即它只扫描profile表中的最后一个 ID 而不是扫描person表,因此请按照下面提到的结构进行操作。type Person struct {    Id      int64   `db:"pId"`    Name    string  `db:"name"`    Email   string  `db:"email"`}然后用asfor person.idlike写你的查询DB.Select(&q, "select (person.id) as pId, person.name, person.email, profile.id, profile.face, profile.hair from profile left join person on person.id = profile.person_id")
随时随地看视频慕课网APP

相关分类

Go
我要回答