如何在 PostgreSQL 中显示一行而不显示其空列?
我想显示表中的所有行以及除空列之外的所有列。
-- SELECT all users
SELECT * FROM users
ORDER BY user_id ASC;
-- SELECT a user
SELECT * FROM users
WHERE user_id = $1;
目前,我的 API 的 GET 请求通过上述查询返回类似这样的内容:
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "[email protected]",
"phone": null,
"website": null
}
有什么方法可以像这样显示它,以便不显示空列吗?
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "[email protected]"
}
I want to show all the rows in my table with all the columns except those columns that are null.
-- SELECT all users
SELECT * FROM users
ORDER BY user_id ASC;
-- SELECT a user
SELECT * FROM users
WHERE user_id = $1;
Currently my API's GET request returns something like this with the above queries:
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "[email protected]",
"phone": null,
"website": null
}
Is there any way I can display it like this so that the null columns aren't shown?
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "[email protected]"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,您在代码中使用序列化(或反序列化)JSON 和对象。更多序列化模块具有特殊参数,如
忽略空值
等。如果您在数据库上生成此JSON格式数据,在内部SQL代码中,那么您可以使用Postgres
jsonb_strip_nulls(JSONB)< /代码> 功能。该函数自动递归地删除 JSONB 中的所有空值键并返回 JSONB 类型。
I understand that you are using serialized (or deserialized) JSON and objects in your code. More serialized modules have special parameters that as
ignore nulls
and etc.If you generate this JSON format data on the DB, in the inside SQL codes, then you can use Postgres
jsonb_strip_nulls(JSONB)
function. This function automatically removes all null values keys in the JSONB recursively and returns the JSONB type.