简体   繁体   English

从Postgres查询格式化嵌套的JSON对象

[英]Format nested JSON object from Postgres query

I want to get a JSON object formatted similar to this: 我想获得一个类似于这样的JSON对象:

{
  "username": "USERNAME",
  "teamname": "TEAMNAME",
  "logs": [
    {
      "log": {
        "log_id": 29,
        "person_id": 3,
        "activity_id": 3,
        "shoe_id": null,
        "logdate": "2016-11-29",
        "distance": null,
        "activitytime": null,
        "sleep": null,
        "heartrate": null,
        "logtitle": null,
        "description": null
      },
      "activity": "Swim", 
      "comments": {
        "comment_id": 1, 
        "description": "This is a comment", 
        "person_id": 1,
        "log_id": 29
       }
   }]
}

Currently I have everything formatted correctly except the comments. 目前,除了评论之外,我的所有格式都正确。 Here is the SQL query I am using: 这是我正在使用的SQL查询:

SELECT p.username, t.teamname, json_agg(json_build_object('log', l.*, 'comments', c.*, 'activity', a.activity)) as logs
        FROM person_tbl p 
        INNER JOIN log_tbl l ON p.person_id = l.person_id 
        INNER JOIN activity_tbl a ON l.activity_id = a.activity_id 
        INNER JOIN comment_tbl c ON c.log_id = l.log_id
        INNER JOIN person_team_tbl pt ON p.person_id = pt.person_id 
        INNER JOIN team_tbl t on t.team_id = pt.team_id 
        WHERE t.team_id = 5
        AND l.logdate > NOW()::date - 7 
        GROUP BY p.username, t.teamname 
        ORDER BY p.username

I'm having trouble getting the comments of each log. 我无法获取每个日志的注释。 Right now, it is returning every comment and repeating the logs (they are not associated). 现在,它返回每条评论并重复日志(它们没有关联)。

Also, how could I get this query to return the username and teamname when everything else is null (like when there are no logs in the past week)? 另外,当其他所有内容都为空时(如上周没有日志的话),如何让这个查询返回usernameteamname

Without an SQLfiddle we do not know what your data (and structure) is so it is difficult to answer your question. 如果没有SQLfiddle,我们不知道您的数据(和结构)是什么,因此很难回答您的问题。 For the NULL case - please modify the WHERE clause like this (deliberately not using COALESCE) 对于NULL情况 - 请修改像这样的WHERE子句(故意不使用COALESCE)

WHERE t.team_id = 5 AND (l.logdate IS NULL OR l.logdate > NOW()::date - INTERVAL '7 day')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM