Question : Multiple UpDate & Select

Hi Folks,

I have a query that needs to be updated frequently (every 15 minutes or so).  At the moment, it's working but hugely inefficient!

I *know* there is a much more efficient way of doing this, but for the life of me I can't get my head around it!

The existing code should demonstrate what I'm doing fairly easily, I've commented it a little too.



SELECT ID, sitename
FROM sites
ORDER BY sitename ASC


      
   
    SELECT COUNT(ID) AS uvcount
    FROM tracking
    WHERE eventdt >= #today# AND sitename = '#getsites.sitename#'
    GROUP BY UUID
   

   
   
    UPDATE sites
    SET uvtoday='#getuv.uvcount#'
    WHERE sitename='#getsites.sitename#'
   

 

Answer : Multiple UpDate & Select

You didn't say which database you're using. But you should be able to do it either with a JOIN or subquery.  Totally untested, but the idea's something like below.  ie Replace the looping and variable with a subquery on the tracking table.

    UPDATE sites
    SET    sites.uvtoday =
            (
          SELECT COUNT(tracking.ID) AS uvcount
            FROM  tracking
            WHERE tracking.eventdt >= #today# AND tracking.sitename = sites.sitename
            )

>   SELECT COUNT(ID) AS uvcount
>    FROM tracking
>    WHERE eventdt >= #today# AND sitename = '#getsites.sitename#'
>    GROUP BY UUID

> UPDATE sites
>    SET uvtoday='#getuv.uvcount#'
> ....

ALSO -  Something seems off about the queries in the loop.  "GetUV" groups by UUID, which suggests there are _multiple_ records.  Yet the UPDATE query only uses the value in the _first_ row??
Random Solutions  
 
programming4us programming4us