嵌套查询更新

时间:2016-10-17 07:50:17

标签: mysql sql

我试图让它运行(带我去弄清楚),但似乎我需要一个嵌套查询来更新工作和我消隐。任何提示/建议将不胜感激。

update `deal_change_log`
set new_value = 'Paying' and old_value = 'Null'
where id in (select item_id from deal_change_log
             where field_key = '458a901560dc06efb78fe365b951dacd3a6a1a11' 
             and `old_value` = 'billing details entered' 
             and `new_value` = 'paying'
             and item_id not in (select item_id from `deal_change_log` d2 where d2.`field_key` = '458a901560dc06efb78fe365b951dacd3a6a1a11' 
             and d2.`log_time` > `log_time`) 
order by item_id);

2 个答案:

答案 0 :(得分:0)

使用别名,

update `deal_change_log`
set new_value = 'Paying' and old_value = 'Null'
where id in (select item_id from deal_change_log d1
             where d1.field_key = '458a901560dc06efb78fe365b951dacd3a6a1a11' 
             and d1.`old_value` = 'billing details entered' 
             and d1.`new_value` = 'paying'
             and d1.item_id not in (select item_id from `deal_change_log` d2 where d2.`field_key` = '458a901560dc06efb78fe365b951dacd3a6a1a11' 
             and d2.`log_time` > d1.`log_time`) 
order by d1.item_id);

答案 1 :(得分:0)

避免使用子查询,因为可以缓慢执行:

  declare @item_id2 varchar(100)
  select @item_id2 =item_id  from `deal_change_log` d2 
          where d2.`field_key` = '458a901560dc06efb78fe365b951dacd3a6a1a11' 
         and d2.`log_time` > `log_time`) order by item_id
  declare @item_id varchar(100)
   select @item_id= item_id  from deal_change_log
         where field_key = '458a901560dc06efb78fe365b951dacd3a6a1a11' 
         and `old_value` = 'billing details entered' 
         and `new_value` = 'paying'
         and item_id not in ( @item_id2)

  update `deal_change_log`
  set new_value = 'Paying' and old_value = 'Null'
   where id in ( @item_id) ;