简体   繁体   中英

Create update query from select sql

I did a select query to find which products have a reference set when they not have a combination, and want to update that value to NULL from the result.

Anyone got an idea on how to build the query for the update?

SELECT QUERY:

SELECT 
  `id_product_supplier` , `id_product` , `id_product_attribute` ,
  `product_supplier_reference` , COUNT( `product_supplier_reference` )
FROM `ps_product_supplier`
GROUP BY `id_product`
HAVING COUNT( `product_supplier_reference` ) >1
AND `id_product_attribute` =0
AND `product_supplier_reference` >0

I want to have an update that is product_supplier_reference = NULL from the result.

try this

update ps_product_supplier  tt inner join(
SELECT 
`id_product_supplier` , `id_product` , `id_product_attribute` , `product_supplier_reference` , COUNT( `product_supplier_reference` )
FROM `ps_product_supplier`
GROUP BY `id_product`
HAVING COUNT( `product_supplier_reference` ) >1
AND `id_product_attribute` =0
AND `product_supplier_reference` >0)t on t.id_product_supplier=tt.id_product_supplier
set tt.product_supplier_reference=null 
Try below script 

 UPDATE ps_product_supplier SET product_supplier_reference = --Value
 FROM
 (
   SELECT  id_product_supplier , id_product , id_product_attribute ,   
   product_supplier_reference , COUNT( product_supplier_reference ) 
   FROM ps_product_supplier 
   GROUP BY id_product 
   HAVING COUNT( product_supplier_reference ) >1 AND id_product_attribute =0      
   AND product_supplier_reference >0
 ) A WHERE --Your Codition 

TRY THIS if you want to simply update the particular column then select only required column in select statement as below and join it for the update:

UPDATE `ps_product_supplier` pps
INNER JOIN (
        SELECT 
          `id_product`
        FROM `ps_product_supplier`
        WHERE `id_product_attribute` =0
        AND `product_supplier_reference` >0
        GROUP BY `id_product`
        HAVING COUNT( `product_supplier_reference` ) >1) p ON p.id_product = pps.id_product
SET pps.product_supplier_reference = NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM