gpt4 book ai didi

mysql - 左连接如何与 sqlx 一起工作

转载 作者:数据小太阳 更新时间:2023-10-29 03:10:37 26 4
gpt4 key购买 nike

我正在尝试使用一个简单的查询将两个表 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}}
]

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

最佳答案

遵循 @zerkms 提供的代码片段我做了一些更改,使我可以无错误地运行程序,并且无需重命名 db 标签。首先,我在 profile struct 中添加了以下代码,让查询识别 person struct

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 指出的重复列名

关于mysql - 左连接如何与 sqlx 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52621745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com