SQL 更新 table 关系在其他 table 中

SQL Update table where Relation is inside other table

你好,我有两个 Table,其中 table 第一个是产品, table 第二个是我想使用这个 SQL 更新的类别,但继续获取语法错误

UPDATE product SET local_delivery = 0,none_local_delivery = 0,
WHERE EXISTS
(SELECT product.local_delivery,product.none_local_delivery 
FROM product
INNER JOIN product_to_category ON product.product_id = 
product_to_category.product_id WHERE
product_to_category.category_id = 90 )

1064 - 你的 SQL 语法有误;查看与您的 MySQL 服务器版本对应的手册,了解在 'WHERE EXISTS 附近使用的正确语法 ( SELECT product.local_delivery, product.none' 在第 4 行

使用以下语法

UPDATE p
SET    local_delivery = 0,
       none_local_delivery = 0
FROM   product AS p
WHERE  EXISTS (SELECT  1
               FROM   product P
                      INNER JOIN product_to_category PCT
                              ON P.product_id =
                                 PCT.product_id
               WHERE  PCT.category_id = 90);  

或以下语法并删除 where exist

UPDATE p
SET    local_delivery = 0,
       none_local_delivery = 0
FROM   product p
       INNER JOIN product_to_category PTC
               ON P.product_id = PTC.product_id
WHERE  product_to_category.category_id = 90  

语法错误是 WHERE.

之前的逗号

您的更新语句然后更新 table 中的所有行或不更新行,具体取决于类别 90 是否存在产品。

我想您宁愿更新类别 90 的所有产品。为此,请将 product_to_category 与您正在更新的产品相关联。如果我的假设是正确的,则查询必须如下所示:

UPDATE product SET local_delivery = 0,none_local_delivery = 0
WHERE EXISTS
(
  SELECT NULL
  FROM product_to_category 
  WHERE product_to_category.product_id = product.product_id
  AND product_to_category.category_id = 90
);

或者更简单一点 IN:

UPDATE product SET local_delivery = 0,none_local_delivery = 0
WHERE product_id IN 
        (SELECT product_id FROM product_to_category WHERE category_id = 90);