为了账号安全,请及时绑定邮箱和手机立即绑定

左连接如何与 sqlx 一起工作

左连接如何与 sqlx 一起工作

Go
鸿蒙传说 2023-04-17 16:04:22
我正在尝试内部连接两个表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}}]我无法弄清楚出了什么问题。
查看完整描述

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`)


查看完整回答
反对 回复 2023-04-17
?
阿晨1998

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)


查看完整回答
反对 回复 2023-04-17
?
UYOU

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")



查看完整回答
反对 回复 2023-04-17
  • 3 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信