结果希望我有一个结构体
type Users struct {
ID int `json:"id"`
Name string `json:"name"`
Age string `json:"age"`
}
Run Code Online (Sandbox Code Playgroud)
我有一个 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
Run Code Online (Sandbox Code Playgroud)
如果存在,我怎样才能使它成为一个动态查询以显示年龄,否则它不会显示它?
不要那样做。相反,为您的Age字段使用可为零的类型。*string或者sql.NullString将是最自然的选择。然后总是选择它,NULL 值将被正确处理。
type Users struct {
ID int `json:"id"`
Name string `json:"name"`
Age *string `json:"age"`
}
Run Code Online (Sandbox Code Playgroud)
然后总是使用:
SELECT id, name, age FROM users
Run Code Online (Sandbox Code Playgroud)
当Age数据库中为 NULL时,它将nil在 Go 中,当它在数据库中不为 NULL 时,它将是一个指向 Go 中字符串的非 nil 指针。