今天遇到个问题,A,B 2张表查询, 如果B中的没有对应的数据,会返回null, 即使 该字段设置是有默认值的。
golang 对于 null 处理 又会出错? 怎么破?
E.G.
query := `SELECT a, b, c, t2.d FROM t_a t1
LEFT JOIN t_b t2 on t1.s = t2.s WHERE t1.s = ? ORDER BY t2.d DESC LIMIT 0 , 1`
row := this.db.QueryRow(query, sessId)
var a, b, c, d int32
err := row.Scan(&a, &b, &c, &d)
d 字段为空,导致err。
解决方式是用 sql.null
query := `SELECT a, b, c, t2.d FROM t_a t1
LEFT JOIN t_b t2 on t1.s = t2.s WHERE t1.s = ? ORDER BY t2.d DESC LIMIT 0 , 1`
row := this.db.QueryRow(query, sessId)
var a, b, c, d int32
e := sql.NullInt64{}
err := row.Scan(&a, &b, &c, &e)
d = int32(e.Int64)