tags:

views:

82

answers:

3

I'm running this query in 2 mysql_query calls. I would like to do the most performant thing and run it in one query. Can anyone optimize this for me:

if(mysql_num_rows(eq("select * 
                        from player_data 
                       where uid = $uid")) == 0 )
      eq("update player_data 
             set uid = $uid, 
                `stat`= REPLACE(`stat`, '$temp_uid', '$uid') 
           where uid = $temp_uid");

Note: eq is just a wrapper function for mysql_query

A: 
if(mysql_num_rows(eq("select 1 from player_data where uid=$uid")) == 0 )
      eq("update player_data set uid=$uid, `stat`=REPLACE(`stat`, '$temp_uid', '$uid') where uid=$temp_uid");

Avoid select * if you just want to get the count of rows in the table.

Will A
You have a point, but a single query is still preferrable
OMG Ponies
+2  A: 

You could try:

eq("update player_data 
       set uid = $uid, 
           `stat`=REPLACE(`stat`, '$temp_uid', '$uid') 
     where uid=$temp_uid 
       and not exists (select * 
                         from player_data 
                        where uid = $uid)");
Joni
Here you can use `select *` inside exists-clause because its not going to generate any result set.
Joni
@Joni: The SELECT on an EXISTS will never execute - EXISTS only returns true on the first match. You could change it to `EXISTS(SELECT 1/0 ...)` and you won't receive a divide by zero error.
OMG Ponies
+1: The fewer the queries, the better
OMG Ponies
A: 

Will A's answer is very good, and if you do need to select a field specify it. Selecting everything is terrible for performance.

VisBits