3 回答
TA贡献1803条经验 获得超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`)
TA贡献2037条经验 获得超6个赞
该错误是由于id从结果中返回两列但将结果存储在两个结构中具有相同字段名称 id 的结构中,您将其实例传递给 DB.Select。尝试捕获单个 id 列并将其传递给结构。
传递多个列但不同的列名,您可以将其用作别名。列别名将是您在其中扫描数据的 Person 结构中的字段:
type Person struct {
PersonId int64 `db:"personId"`
Name string `db:"name"`
Email string `db:"email"`
}
var q []Profile
DB.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)
TA贡献1878条经验 获得超4个赞
您需要像下面我描述的那样更改结构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")
- 3 回答
- 0 关注
- 120 浏览
添加回答
举报