【发布时间】:2019-03-08 08:55:07
【问题描述】:
我正在尝试通过一个简单的查询来内部连接两个表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}}
]
我无法弄清楚出了什么问题。
【问题讨论】:
-
结果集中不能有多个同名的列,它只是
mysqlcli 处理它的功能 -
好吧,我不知道怎么做。我尝试使用
profile.id as profile_id而不是profile.id,但它没有用。你能给我提供更多帮助吗? -
我用谷歌搜索“go sqlx join select”,这是第一个结果:snippets.aktagon.com/snippets/…
-
sqlx 中的左连接(或任何连接)绝对没有什么独特之处。 sqlx 只处理数据库返回的行——查询背后的逻辑与 sqlx 100% 无关。