Re: How to optimize this query ?

From: "ProgHome" <proghome(at)silesky(dot)com>
To: "'Stephan Szabo'" <sszabo(at)megazone(dot)bigpanda(dot)com>
Cc: "'Franco Bruno Borghesi'" <franco(at)akyasociados(dot)com(dot)ar>, <pgsql-sql(at)postgresql(dot)org>
Subject: Re: How to optimize this query ?
Date: 2003-08-28 01:01:27
Message-ID: 037f01c36cff$ec09c770$0700a8c0@Office3
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

You were right, Stephan !
The query below is still not correct ... because the second line
shouldn't be shown !
Now I really don't know how I could rewrite this without a subquery
because it doesn't seem to be possible with some LEFT or INNER joins !
Do you have an idea ?

-----Original Message-----
From: Stephan Szabo [mailto:sszabo(at)megazone(dot)bigpanda(dot)com]
Sent: Wednesday, August 13, 2003 2:29 PM
To: ProgHome
Cc: 'Franco Bruno Borghesi'; pgsql-sql(at)postgresql(dot)org
Subject: RE: [SQL] How to optimize this query ?

On Wed, 13 Aug 2003, ProgHome wrote:

> I tried with some LEFT JOINS, which give me the possibility to keep
> the information of the right table.
>
> I have now the following query, which is 10 times faster !!! (from 16s
> to 1.6s)
> But I'd like to remove the last subquery, to see if it faster ;)
>
>
> -------------------------
>
> SELECT lead. *
> FROM lead
> LEFT JOIN purchase ON ( lead.id = purchase.lead_id )
> LEFT JOIN affiliate_lockout ON ( lead.affiliate_id =
> affiliate_lockout.affiliate_locked_id )
> WHERE (
> exclusive IS NULL OR (
> exclusive = 0 AND nb_purchases < 3
> )
> ) AND id NOT
> IN (
>
> SELECT lead_id
> FROM purchase
> INNER JOIN member_exclusion
> WHERE purchase.member_id = member_exclusion.member_id_to_exclude AND
> purchase.member_id = 21101
> ) AND (
> affiliate_lockout.member_id <> 21101 OR affiliate_lockout.member_id IS
> NULL
> ) AND purchase.member_id <> 21101
> GROUP BY lead.id

As I replied to Franco for his query below, I believe this query is not
equivalent to your original query for a few cases, but those might not
come up.

If you had a row in lead like
id = 2, affiliate_id = 2
And rows in affiliate_lockout like:
affiliate_locked_id=2, member_id=21101
affiliate_locked_id=2, member_id=31101
should this row in lead be shown or not?

In the original query I think it would not (because lead.affiliate_id
was
IN the affiliate_lockout table where member_id=21101). In the above
query
I think it will, because one of the joined tables will have the lead
information and a member_id that is not equal to 21101.

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Joe Conway 2003-08-28 01:02:38 Re: How to return a record set from function.
Previous Message Joe Conway 2003-08-28 00:40:17 Re: length of array