使用postgres在查询中为json_build_object表达JS结构JSON响应并添加分页参数

时间:2018-07-25 12:05:29

标签: json node.js postgresql express

我有以下查询,并且运行良好并正在发送响应。

const query =
  `SELECT json_build_object('nct_id', s.nct_id, 'overall_status', s.overall_status, 'phase', s.phase, 'brief_title', s.brief_title, 'country', countries.name, 'eligibilities',
    (SELECT json_agg(json_build_object('criteria', e.criteria, 'gender', e.gender))
     FROM eligibilities e WHERE s.nct_id = e.nct_id), 'facilities',
         (SELECT json_agg(json_build_object('status', f.status, 'name', f.name, 'city', f.city, 'country', f.country))
          FROM facilities f WHERE s.nct_id = f.nct_id AND f.country LIKE $1), 'interventions',
          (SELECT json_agg(json_build_object('intervention_type', i.intervention_type, 'name', i.name, 'description', i.description))
           FROM interventions i WHERE s.nct_id = i.nct_id), 'design_groups',
           (SELECT json_agg(json_build_object('group_type', dg.group_type, 'title', dg.title, 'description', dg.description))
            FROM design_groups dg WHERE s.nct_id = dg.nct_id), 'sponsors',
            (SELECT json_agg(json_build_object('agency_class', sp.agency_class, 'lead_or_collaborator', sp.lead_or_collaborator, 'name', sp.name))
             FROM sponsors sp WHERE s.nct_id = sp.nct_id)) json
FROM studies s
INNER JOIN countries ON countries.name SIMILAR TO $1 AND countries.nct_id = s.nct_id
INNER JOIN keywords ON keywords.nct_id = s.nct_id AND keywords.downcase_name SIMILAR TO $2
WHERE s.overall_status NOT SIMILAR TO '(Suspended|Withheld|Completed|No longer available|Withdrawn)' LIMIT 10 OFFSET ($3 - 1) * 10`;

db.map(query, [country + '%','%' + cancerType + '%',page], a => a.json)
.then(data => {
    res.send(data);
})
.catch(error => {
    console.log(error);
    res.status(500).send('Error occured');
});
});

响应的结构为:

[
  {
    "key1": "value1",
    "key2": "value2",
    ..........
  }
]

我希望结构如下:

"data": [
          {
            "key1": "value1",
            "key2": "value2",
            ..........
          }
        ],
"total_results": "number_of_total_results",
"total_pages": "number_of_total_pages"

问题1。如何实现上述JSON响应结构?

当我尝试使用 count()OVER()*获得total_results时,它出现在上述数据中的每组结果中。

第二季度。如何用计数和页面总数实现正确的分页,以及如何在给定方案中实现它?

谢谢。

0 个答案:

没有答案