我试图将查询结果扫描到一个res结构中。
代码已经编译通过,查询也成功执行,但结果数组却包含了这样的默认值:
[{0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0} {0 0 0}]
此外,结果数组的长度与查询结果应该有的长度完全相同。 当我在PostgreSQL shell中尝试生成查询时,它会正确返回结果。
代码:
type res struct{
id int
number int
user_id int
}
func getDataJoin(){
new := []res{}
db.Db.Table("users").Select("users.id as id, credit_cards.number as number, credit_cards.user_id as user_id").Joins("left join credit_cards on credit_cards.user_id = users.id").Scan(&new)
fmt.Println("user\n",new)
}
生成的查询:
SELECT users.id as id, credit_cards.number as number, credit_cards.user_id as user_id FROM "users" left join credit_cards on credit_cards.user_id = users.id
数据库查询结果
id | number | user_id
----+--------+---------
1 | 1 | 1
1 | 2 | 1
2 | 1 | 2
2 | 2 | 2
3 | 1 | 3
3 | 2 | 3
(6 rows)