1

我正在尝试内部连接两个表personprofile使用一个简单的查询,该查询似乎适用于 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}}
]

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

4

3 回答 3

1

@zerkms提供的代码片段之后,我做了一些更改,使我能够运行程序而不会出现错误并且不会重命名 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`)

避免@zerkms指出的重复列名

于 2018-10-04T13:02:57.940 回答
0

您需要更改结构中的db名称,person如下所示,因为将有两列具有相同的名称,即id,因此它仅扫描表中的最后一个 idprofile而不是扫描person表,因此请按照下面提到的结构进行操作。

type Person struct {
    Id      int64   `db:"pId"`
    Name    string  `db:"name"`
    Email   string  `db:"email"`
}

as然后用for 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")
于 2018-10-03T11:10:18.993 回答
0

该错误是由于从结果中返回两id列,但将结果存储在两个结构中具有相同字段名称 id 的结构中,您将其实例传递给 DB.Select。尝试捕获单个 id 列并将其传递给 struct。

传递多列但不同的列名称,您可以将其用作别名。列别名将是您正在扫描数据的 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)
于 2018-10-03T11:11:02.480 回答