首页 > 解决方案 > sql UPDATE SET WHERE 条件给出错误 1242

问题描述

我收到错误 1242 子查询返回超过 1 行

如果产品包含这些添加,我想要更新列 bio 并将其设置为“bio-plant”。

UPDATE product
SET bio = 'bio-plant'
WHERE ( SELECT distinct product.Id_Product
        FROM product , product_has_additions
        WHERE product_has_additions.code IN ('E170', 'E220', 'E296', 'E300', 'E306', 'E322', 'E330', 'E333', 'E334', 'E335', 'E336', 'E341', 'E392', 'E400', 'E401', 'E402', 'E406', 'E407', 'E410', 'E412', 'E414', 'E415', 'E422', 'E440', 'E464')
        AND product.Id_Product = product_has_additions.Id_Product
       );

标签: mysqlsql-updateconditional-statementsmysql-error-1242

解决方案


我认为你真正需要的是两个表的连接:

UPDATE product p
INNER JOIN product_has_additions a
ON a.Id_Product = p.Id_Product
SET p.bio = 'bio-plant'
WHERE a.code IN (
  'E170', 'E220', 'E296', 'E300', 'E306', 'E322', 'E330', 'E333', 
  'E334', 'E335', 'E336', 'E341', 'E392', 'E400', 'E401', 'E402', 
  'E406', 'E407', 'E410', 'E412', 'E414', 'E415', 'E422', 'E440', 'E464'
)

或者,使用EXISTS

UPDATE product p
SET p.bio = 'bio-plant'
WHERE EXISTS (
  SELECT 1 FROM product_has_additions a
  WHERE a.Id_Product = p.Id_Product
    AND a.code IN (
     'E170', 'E220', 'E296', 'E300', 'E306', 'E322', 'E330', 'E333', 
     'E334', 'E335', 'E336', 'E341', 'E392', 'E400', 'E401', 'E402', 
     'E406', 'E407', 'E410', 'E412', 'E414', 'E415', 'E422', 'E440', 'E464'
  )
)

推荐阅读