【问题标题】:获取 1:postgreSQL 中的许多关系为(对象关系)?
【发布时间】:2022-01-23 03:00:47
【问题描述】:

我有两个名为 userpost 的表,它们的数据如下:

用户表

 id | first_name | second_name 
  1     John          Doe
  2     Ellis         Mount               

帖子表

 id |   topic        |    body        |   author_id
  1    Internet       ...some text          1
  2    Web 3.0        ...some text          2      

所以我的问题是如何查询posts,其中author 用户作为引用创建帖子的用户的对象。

[
   { 
     id:1,
     topic: Internet,
     body: ...some text, 
     author_id: 1
     author: {
       first_name: John,
       last_name: Doe
     }
   },

   { 
     id: 2,
     topic: Web 3.0,
     body: ...some text, 
     author_id: 2
     author: {
       first_name: Ellis,
       last_name: Mount
     }
   }
]

所以,为了达到这个目的,我尝试了类似的方法,使用 `inner join:

SELECT *
FROM post 
INNER JOIN user
ON post.author_id = user.id;

不幸的是,这没有获取我想要的数据......所以如果有人知道如何查询这个请帮忙!

【问题讨论】:

  • 你是说你想要 JSON 格式的输出吗?
  • @JonathanWillcock 是的,你可以这么说或者像 MongoDB 一样工作。
  • this answer 对您有帮助吗?

标签: database postgresql


【解决方案1】:

您可以使用 JSON 格式并创建 JSON 文件。

Demo

SELECT
  post.*,
  json_build_object(
    'first_name',
    first_name,
    'last_name',
    second_name
  ) as author
FROM post 
INNER JOIN "user"
ON post.author_id = "user".id;

【讨论】:

  • 谢谢兄弟,这成功了。
猜你喜欢
  • 2011-10-05
  • 1970-01-01
  • 2019-07-17
  • 2011-10-16
  • 1970-01-01
  • 2017-05-10
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多