【发布时间】:2018-09-18 18:08:45
【问题描述】:
the result wanted我有一个结构体
type Users struct {
ID int `json:"id"`
Name string `json:"name"`
Age string `json:"age"`
}
我有一个 mysql 数据库,其中一些年龄值为零,所以基本上为了使其动态化,我一直在寻找解决方案。 “年龄字符串json:-”如果从mysql返回值nil,则隐藏该字段。
我做了两个查询
query1: select id,name,age from users where age is not null
query2: select id,name from users where age is null
如果存在则如何使其成为动态查询以显示年龄,否则不显示年龄?
【问题讨论】:
-
你不能在 MySQL 中创建动态列。
-
无法使用不同的 json 标签创建动态结构或隐藏值。
-
@RaymondNijland 我在谈论将显示为 json 值的结果,该表有一行名为 age 但它有一些空值,所以我想控制年龄为空的结构它只会显示 id 和用户,否则它将显示所有字段
-
@Medone 在使用 sql.NullInt64 之前,您必须将 int 转换为 int64。如果您选择替代方案,您也可以使用
COALESCE(age, 0)。 -
@Medone 在 json 标记中使用
,omitempty,如果您想避免 json 中的null属性。