Come posso unire le tabelle a un aggiornamento
-
03-07-2019 - |
Domanda
Ho la seguente 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);
che cerca record con lo stato 5 in una determinata città che hanno più di 6 mesi (la data per la quale è memorizzata a Los Angeles). Questo restituisce circa 4k risultati. Vorrei aggiornare il valore dello stato su 1 su ciascuno di questi record, e quindi il mio aggiornamento è simile a:
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);
ma si blocca e blocca il db. Ho il sospetto che ci sia un problema perché non c'è join, ma provo qualcosa del tipo:
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);
e ovviamente non funzionerà perché non c'è un 'da' in un aggiornamento.
Modifica > Sto usando MySQL
Soluzione
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
)
Altri suggerimenti
Per MySQL
, puoi usare la vecchia sintassi del join:
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)
Vorrei fare questo:
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)
Vedi anche:
Aggiornamento SQL da una tabella a un altro sulla base di una corrispondenza ID
In SQL Server 2005 funzionerà:
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);