Postgresql - 在另一个select语句中使用From中的变量

时间:2014-09-04 01:36:35

标签: sql postgresql query-optimization

我要做的是将查询优化95%,作为学习psql的任务的一部分。我想要的是所有拥有与第三大借书相同或更大的客户。

explain analyze
select clb.f_name, clb.l_name, noofbooks 
from 
      (select f_name, l_name, count(*) as noofbooks 
      from customer left join loaned_book on customer.customerid = loaned_book.customerid 
      group by f_name, l_name) as clb,
      (select f_name as fname, l_name as lname, count(*) as noofbooksf 
      from customer left join loaned_book on customer.customerid = loaned_book.customerid
      group by fname, lname order by noofbooksf  desc  LIMIT 1 OFFSET 2) as clb1
where noofbooks  >= noofbooksf 
order by noofbooks desc; 

这就是我到目前为止,它已经优化到高80但是这两个连接增加了成本。因此我要做的就是做一次加入。然后使用结果获取它的第三个元素。我想创建一个临时视图,但我确信会有更好的方法。

感谢。

1 个答案:

答案 0 :(得分:0)

如果你想要拥有第一或第二大借书的人,那就去做:

select c.f_name, c.l_name, count(lb.customerid) as noofbooks 
from customer c left join
     loaned_book lb
     on c.customerid = lb.customerid 
group by c.f_name, c.l_name
order by noofbooks desc
limit 3;

如果你担心关系:

select f_name, l_name, noofbooks
from (select c.f_name, c.l_name, count(lb.customerid) as noofbooks,
             rank() over (order by noofbooks desc) as seqnum
      from customer c left join
           loaned_book lb
           on c.customerid = lb.customerid 
      group by c.f_name, c.l_name
     ) clb
where seqnum <= 3;