Subject Select joined with a view is slow
Author Mark Shapiro
Consider the following (partial) table structures:

People:
pid integer not null primary key

PeoplePictures:
pictureID integer not null primary key
pid integer not null foreign key people.pid


And a view:
create view V_PeoplePicturesCount (pid, photocount) as
select VPC_people.pid, count(VPC_peoplepictures.pid)
from people VPC_people
left join peoplepictures VPC_PeoplePictures on
VPC_people.pid=VPC_peoplepictures.pid
group by VPC_people.pid;

This view then returns a list of PID and the count of pictures for that PID.

If I select from this view, the result set is returned relatively quickly,
O(n).

If I select from the People table or the PeoplePictures table, the result
set is returned quickly, O(n).

If I do this select:

select v_peoplepicturescount.*
from people sel_people
left join v_peoplepicturescount on v_peoplepicturescount.pid=sel_people.pid

(joining the people table and the view on pid)
the result set is returned in what appears to be at least O(n^2) if not
O(n^n)

I've made sure that all table references in the view and in the select
statement are to aliases. (VPC_* for the view, sel_* for the table)

What should be my next step in trying to improv the time of this query?
There are already indices on all of the fields involved, as they are all
primary or foreign keys. I tried changing count to both min and max, to
take further advantage of the indices, and neither made any noticable
difference.

Thanks.
-Mark