简体   繁体   English

使用条件优化 Postgres 查询

[英]Optimize Postgres query with conditions

I have a query where I am joining tables and checking if the particular incident has failed a processing with error kode 76,75,10 and checking another condition where i checked if course has only 1 incident.我有一个查询,我正在加入表格并检查特定事件是否未能通过错误代码 76、75、10 进行处理,并检查我检查课程是否只有 1 个事件的另一个条件。

Is there any way to check if course has only 1 incident then only the 1st condition happens in a single query??有没有办法检查课程是否只有 1 个事件,然后在单个查询中只发生第一个条件?

Tried with case --> when but not sure尝试过 case --> when 但不确定

select * from course c where id in(select i.course_id from incident i
 join report r on i.report_id=r.id
 join error e on e.report_id=r.id
 join error_code ek on e.error_code_id=ek.id where errorcode in (76,75,10)) and
     (select count(*) from incident i where i.course_id = c.id) =1

If both conditions in and are fulfilled, then the single incident of course must be of errorcode 76,75 or 10. So take all incidents with that errorcodes and return only those courses for which there is just one such incident.如果and中的两个条件都满足,那么单个incident course必须是错误代码 76,75 或 10。因此,获取所有带有该错误代码的事件,并仅返回只有一个此类事件的课程。

select * from course c where id in (
  select i.course_id
  from incident i
  join ... -- r,e,ek on obvious conditions
  where errorcode in (76,75,10)
  group by i.course_id
  having count(distinct i.id) = 1
)

(I used distinct since it isn't clear what kind are the relations i->r->e->ek of. If all of them are many to one, then distinct isn't necessary, otherwise it must be there to avoid false-duplicate i.id s due to joins.) (我使用distinct因为不清楚i->r->e->ek的关系是什么类型。如果它们都是多对一的,那么distinct是不必要的,否则必须避免由于连接导致的错误重复i.id 。)

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

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