【问题标题】:SQL join query (joined field as a json object)SQL 连接查询(连接字段作为 json 对象)
【发布时间】:2021-10-26 19:36:12
【问题描述】:

我正在使用 PostgreSQL,我正在使用 Nodejs 和 PG 包。我有这些表:

request_tbl:

 req_id |  customer_id  | details              
----+--------------------------------------
  1     |    1          | something
  

customers_tbl:

 cust_id |  full_name | age             
----+--------------------------------------
  1      |  tarik hh  | 23
    

我需要一个在将其转换为 json 后给出此输出的查询。

这是一个左连接,但我需要将连接的列作为对象。

  [
    {
       "req_id":"1" , 
       "details":"something" ,
       "customer":{
                    "cust_id":"1",
                    "full_name":"tarik hh"
                  }
    }
      
  ]

【问题讨论】:

  • 避免在问题正文中发布问题的解决方案。您可以将其发布为答案。

标签: node.js json postgresql pg


【解决方案1】:

使用 postgresql 内置的 json_build_object 函数并像这样创建自己的函数:

CREATE FUNCTION get_req_w_cust(
  req_id_in int, 
  out results json
) AS $$
BEGIN
  SELECT json_build_object(
    'req_id', request_tbl.req_id,
    'details', request_tbl.details,
    'customer', json_build_object(
      'cust_id', customers_tbl.cust_id,
      'full_name', customers_tbl.full_name
    )
  ) INTO results
  FROM request_tbl, customers_tbl
    WHERE request_tbl.customer_id = customers_tbl.cust_id
    AND request_tbl.req_id = req_id_in
END
$$ language plpgsql;

然后你可以从你的代码中访问它

let {rows: [{results}] = await pg.query('select get_req_w_cust($1) AS results',[id]);

或者只使用查询而不将其包装在函数中。

【讨论】:

  • 感谢回复,我遇到语法错误
  • 感谢您对您的查询进行了一些修改后我得到了它的工作,我会发布最终结果
猜你喜欢
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多