¿Cómo puedo unir tablas en una actualización?
-
03-07-2019 - |
Pregunta
Tengo la siguiente consulta:
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);
que busca registros con estado 5 en una ciudad en particular que tienen más de 6 meses (la fecha para la cual se almacena en LA). Esto devuelve unos 4k resultados. Me gustaría actualizar el valor del estado a 1 en cada uno de esos registros, por lo que mi actualización se ve así:
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);
pero se detiene y bloquea la db. Sospecho que hay un problema porque no hay ninguna combinación, pero intento algo como:
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);
y, obviamente, no funcionará porque no hay "desde" en una actualización.
editar > Estoy usando MySQL
Solución
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
)
Otros consejos
Para MySQL
, puede usar la sintaxis de unión anterior:
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)
Haría esto:
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)
Ver también:
actualización de SQL de una tabla a otro basado en una coincidencia de ID
En SQL Server 2005 esto funcionará:
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);