0

I need to check and update with same query my database. The error says it is not possble to update same table which is included in the select statement. Is there any workaround of this to happen in 1 mysql query? Here is the query:

 $query='update option_values_to_products set available="0" where id in (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where 
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id )';
thecore7
  • 484
  • 2
  • 8
  • 29

2 Answers2

2

Yes, this is a nagging feature of mysql and there is a workaround to it: wrap the subquery within the IN() clause into another subquery.

update option_values_to_products set available="0" where id in (select id from (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where 
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and 
o.name="Size" group by ovtp.id ) as t)
Shadow
  • 33,525
  • 10
  • 51
  • 64
0

Avoid using nested queries for many reasons like performance and memory issue, also it can be very hard to be understood for the next developers

Good practice
Split your query into 2 parts :

<?php
 $qSelect = 'select ovtp.id from option_values ov,option_values_to_products ovtp,options o where 
             ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and 
             o.name="Size" group by ovtp.id';

  $res = DATABASE_MANAGER::exec($qSelect);

  $qUpdate = 'update option_values_to_products set available="0" where id in (' . implode(",", $res) .')';
  $res2 = DATABASE_MANAGER::exec($qUpdate);
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45