优化嵌套的sql查询

时间:2018-02-13 16:33:02

标签: sql postgresql query-optimization greatest-n-per-group

我正在尝试优化以下查询,该查询每50秒运行一次以提高性能。

select * from event se1  
where id = (select min(id) from event se2 where
se1.sub_id=se2.sub_id and se2.state = 'PENDING' and se2.il_flag= true)  
and not exists (select id from event se2 where se1.sub_id=se2.sub_id
and se2.state in ('ACCEPTED', 'FAILED', 'INPROCESS'))

提出更好的查询以改善其性能的任何方向? (postgres 9.6)。感谢帮助。

活动表

Id              sub_id              state       idl_flag 
1                 23009            Pending        true
2                 23009            Accepted       true
3                 23009            Pending        true
4                 23009            Pending        true
5                 23010            Pending        true
6                 23010            Pending        true
7                 23011            Pending        true
8                 23012            Pending        true

上表应该返回

       5                 23010            Pending       true
       7                 23011            Pending       true

3 个答案:

答案 0 :(得分:0)

您可以使用事件表进行联接,但对此部分使用为空条件:

and not exists (select id from event se2 where se1.sub_id=se2.sub_id
and se2.state in ('ACCEPTED', 'FAILED', 'INPROCESS'))

pelase check How to write "not in ()" sql query using join

但无论如何都要尽量避免使用嵌套查询。

答案 1 :(得分:0)

我想出了这个查询,欢迎任何更好的查询建议。

select se1.* from event se1 join 
  (select sub_id,min(id) as id from event  where state='PENDING' and
           il_flag=false group by sub_id)se2 
   on se1.id=se2.id 
  left join (select sub_id from 
  event se3 where se3.state in ('ACCEPTED', 'FAILED', 'INPROCESS'))se4 
on se1.sub_id=se4.sub_id where se4.sub_id is null

答案 2 :(得分:0)

你在答案中所做的事情与你提出的问题有所不同 - 原始答案中没有任何关于“错误”状态的特殊情况。

基于你原来的问题,我为你做了一点小提琴,它的运行速度比原来快得多,但我讨厌嵌套的子查询。我把它全部考虑到CTE中,这样你就可以选择你想要的状态,只是为了向你展示一种不同的方法。这可能只是个人偏好,但恕我直言,我的版本比原版更容易阅读!

SQL Fiddle - CTE Example