首页 > 解决方案 > 关于最大创建时间和分组依据的 Postgres 查询帮助

问题描述

我有一个复杂的场景,我无法理解。所以我们有一个标准化的 Postgres 数据库。

图片一查询

select id, rule_id, status, risk_level, creationtime, cloudaccount_id, organization_id, description,
       reg_id, pro_id, function_id, category_id, group_id, resource_id

from risk_child

图 2 查询

select ser_id, creationtime, cloud_account_id, owner_id, reg_id, organization_id, pro_id, record_creation_time
       resource_id
from resource

挑战在于我们有一个字段被调用Rules,并且每个字段Rule都会有多个我们想要触发一个查询,该查询将根据具有多个资源的单个规则为resource我们提供表中的最新条目。risk_child

我遇到了一个查询,但由于某种原因它不起作用。

select rc.id,rc.resource_id,max(rc.creationtime)as "create_date_time",rl.rule_tag,rc.status,rc.risk_level,
       rc.user_id,rc.cloudaccount_id,rc.organization_id,rc.description,r.region,
       p.provider,f.function_name,c.category_name,g.group_name,rc.signature_status
from risk_child rc, resource rs,category c, function f , g_by g,
     provider p, region r, rule rl,service s
where rc.resource_id = rs.resource_id and c.id  = rc .category_id and 
      rc.function_id = f.id and rc.group_id = g.id and rc.pro_id = p.id and rc.rule_id = rl.id and
      rc.reg_id = r.id and s.id = rs.ser_id and rc.rule_id >=145 and 
      (rc.creationtime in(select max(creationtime) from risk_child group by resource_id) or 
      rc.creationtime in (select max(creationtime) from risk_child group by rule_id))

group by rc.creationtime,rl.rule_tag,rc.status,rc.risk_level,
       rc.user_id,rc.cloudaccount_id,rc.organization_id,rc.description,r.region,
       p.provider,f.function_name,c.category_name,g.group_name,rc.id,rc.resource_id,rc.signature_status
order by rc.id asc

输出没有给我们基于creationtimein的最新记录risk_child

查询 #1 的结果

查询 #2 的结果

标签: sqlpostgresqlgroup-by

解决方案


如果我理解你的问题是正确的,你想要一个多关系获取,其中每个源对象只显示最新的目标对象。通常,GROUP BY请求不适合此。在我看来,GROUP BY引用聚合列的子句也没有意义。

但这DISTINCT ON相对容易:

SELECT DISTINCT ON(rs.resource_id) rs.resource_id, rc.creation_time, ...
FROM resource rs JOIN risk_child rc ON rs.resource_id = rc.resource_id ...
WHERE ...
ORDER BY rs.resource_id, rc. rc.creation_time DESC, ...

DISTINCT ON子句确保每个资源在结果中仅出现一次。为了让它始终是最新的风险孩子,您必须按 排序,但在这种情况下creation_time,Postgres 还要求您按列排序。DISTINCT ON


推荐阅读