Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Rewrite subselect with using a join

by Anonymous Monk
on Jun 02, 2005 at 01:25 UTC ( #462714=snippet: print w/replies, xml ) Need Help??
Description: Due to an old version of mysql, I had to rewrite a subselect and I decided not to use a join. This is what I cam up with. The subselect looks like this: select object_id from mw_export_record where object_id not in (SELECT object_id from mw_export_record where table_object='advertisers');
my $sth = $dbh->prepare("select object_id from mw_export_record where 
+table_object = 'advertisers'");
@results = grep $_, map{ $_->[0] } @{$sth->fetchall_arrayref};
@results = qw/NULL/ if (@results == 0);
$sth = $dbh->prepare("select object_id from mw_export_record where obj
+ect_id not in (" . join(',',  @results) . ")");
With special thanks to BUU
Replies are listed 'Best First'.
Re: Rewrite subselect with using a join
by dbwiz (Curate) on Jun 02, 2005 at 07:53 UTC

    You were using the wrong join.

    Your snippet is moving computation from a database server to a client application, and it's doing that whitout any particular need.

    The canonical way of transforming your query should go through a table JOIN. However, since you are subquerying the same table, your nested query is nothing more than this:

    select object_id from mw_export_record where table_object != 'advertisers'; -- <-- operator change

    The inner part of your query is selecting all the IDs containing 'advertisers', while the outer part is saying "don't take any record from this list."

    Not only you are computing in the client what should be done in the server, but you are also telling the server to do something unnecessarily complex and heavy that it should not have been doing in the first place.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://462714]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2020-12-02 03:58 GMT
Find Nodes?
    Voting Booth?
    How often do you use taint mode?

    Results (28 votes). Check out past polls.