使用Where子句中的Join的MySQL更新表

时间:2018-08-27 08:51:14

标签: mysql sql-update

我正在尝试使用where子句中的联接更新表。我编写了以下代码

UPDATE  order_history SET Paidvalue = Paidvalue + item_id*1.1
    WHERE  type='addpack'
      and  Addstatus='Active'
      and  ( SELECT  count(i.ip)
                from  ip_ptc i
                inner join  order_history o  ON o.user_id=i.user_id
                                           and  i.date='2018-08-17'
           )>=4

它给出了错误You can't specify target table 'order_history' for update in FROM clause,我需要比较基于user_idorder_history表中的ip_ptc引用的计数。我怎么了

2 个答案:

答案 0 :(得分:2)

该错误表示您同时更新了从中选择的表。您可以通过在子查询中建立一个临时表来克服这个问题

UPDATE order_history 
SET Paidvalue = Paidvalue + item_id*1.1
WHERE type='addpack' and Addstatus='Active'
and 
(
  select * from 
  (
    select count(i.ip) 
    from ip_ptc i 
    inner join order_history o on o.user_id=i.user_id and i.date='2018-08-17'
  ) tmp
) >= 4

要正确计数,请尝试

UPDATE order_history h
JOIN 
(
    select user_id, count(i.ip) as cnt
    from ip_ptc 
    where ip_ptc.date = '2018-08-17'
    group by user_id 
) t on t.user_id = h.user_id and t.cnt >= 4
SET Paidvalue = Paidvalue + item_id*1.1
WHERE type='addpack' and Addstatus='Active'

答案 1 :(得分:0)

它稍微修改了where子句,效果很好

 UPDATE order_history SET Paidvalue = Paidvalue + item_id*1.1 
 WHERE type='addpack' and Addstatus='Active' 
 and ( select * from ( select count(i.ip) from ip_ptc i inner join order_history o on o.user_id=i.user_id and i.date='2018-08-27' AND o.type='addpack' and o.Addstatus='Active' ) tmp)>=4