Question

I have the following query:

select      count(L.ID)
from        LA inner join L on (LA.leadid = L.ID)
where       L.status = 5
and         L.city = "cityname"
and         Date(LA.Datetime) < Date_Sub(Now(), INTERVAL 6 MONTH);

which looks for records with status 5 in a particular city that are older than 6 months (the date for which is stored in LA). This returns about 4k results. I would like to update the value of the status to 1 on each of those records, and so my update looks like:

update      L, LA
set         L.status = 1
where       L.status = 5 
and         L.city = "cityname" 
and         Date(LA.SomeDatetime) < Date_Sub(Now(), INTERVAL 6 MONTH);

but it stalls out and locks the db. I suspect there is a problem because there is no join, but I try something like:

update      L, LA
from        L inner join LA on (L.OID = LA.leadid)
set         L.status = 1
where       L.status = 5 
and         L.syscity = "cityname" 
and         Date(LA.SomeDatetime) < Date_Sub(Now(), INTERVAL 6 MONTH);

and it obviously won't work because there is no 'from' in an update.

edit> I'm using MySQL

Was it helpful?

Solution

update      L
set         L.status = 1
where       L.status = 5 
and         L.city = "cityname" 
and         EXISTS (
  select * from LA 
  where Date(LA.SomeDatetime) < Date_Sub(Now(), INTERVAL 6 MONTH)
  and LA.leadid = L.ID
)

OTHER TIPS

For MySQL, you may use old join syntax:

UPDATE  l, la
SET     l.status = 1
WHERE   l.status = 5
  AND   l.city = "cityname"
  AND   la.leadid = l.id
  AND   DATE(la.datetime) < DATE_SUB(NOW(), INTERVAL 6 MONTH)

I would do this:

update L
set status = 1
from LA
where L.OID = LA.leadid
and L.status = 5
and L.syscity = "cityname"
and Date(LA.SomeDatetime) < Date_Sub(Now(), INTERVAL 6 MONTH)

See also:

SQL update from one Table to another based on a ID match

In SQL Server 2005 this will work:

Update L
   set L.status = 1
from
   L
   --
   JOIN LA
      on (LA.leadid = L.id)
where
   L.status = 5
   and L.city = "cityname"
   and Date(LA.Datetime) < Date_Sub(Now(), INTERVAL 6 MONTH);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top