如何在更新时连接表

时间:2009-03-02 22:40:24

标签: mysql sql join sql-update

我有以下查询:

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);

查找特定城市中状态为5且年龄超过6个月(日期存储在洛杉矶)的记录。这将返回大约4k的结果。我想在每个记录上将状态值更新为1,因此我的更新如下所示:

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);

但是它会停止并锁定数据库。我怀疑存在问题,因为没有连接,但我尝试了类似的事情:

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);

它显然无效,因为更新中没有'from'。

编辑&gt;我正在使用MySQL

4 个答案:

答案 0 :(得分:7)

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
)

答案 1 :(得分:3)

对于MySQL,您可以使用旧的连接语法:

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)

答案 2 :(得分:1)

我会这样做:

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)

另见:

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

答案 3 :(得分:1)

在SQL Server 2005中,这将起作用:

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);