sql - 关于最大创建时间和分组依据的 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
输出没有给我们基于creationtime
in的最新记录risk_child
解决方案
如果我理解你的问题是正确的,你想要一个多关系获取,其中每个源对象只显示最新的目标对象。通常,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
推荐阅读
- react-native - 尽管输入了数据,但仍会触发 Formik 验证错误
- api - 如何将带有动态表格的网页抓取到 Google 表格中
- c++ - Openssl C/C++ 以编程方式从模数和指数中获取 RSA 公钥
- reactjs - React Native axios api 调用 Shopify
- javascript - 另一个可折叠部分中的可折叠部分不会足够展开
- python - Xpath如何检查给定父节点是否存在子元素?
- bazel - 如何在 Bazel 的 WORKSPACE 中设置 ENV VAR
- elasticsearch - Elasticsearch 中的“exists”过滤器是否需要索引
- excel - 在 Google 表格中编写动态引用(如 Excel 中的“#”)
- python - 找不到tomcat用户python模块