使用INNER JOIN进行SQL更新

时间:2013-01-23 23:02:55

标签: mysql sql inner-join

我正在尝试使用此查询

UPDATE products  
SET products.product_price = '87.00000'
FROM products
INNER JOIN product_category
ON products.product_id = product_category.product_id 
WHERE product_category.category_id = '64'

但是我收到此错误:#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM table products INNER JOIN table product_category ON prod' at line 3

我没有看到任何语法错误。我在这个论坛的例子中提出了这个问题。

4 个答案:

答案 0 :(得分:3)

删除FROM products行。 并把 在SET ...子句之前的WHERE行。

要明确:

UPDATE ...
JOIN ...
SET ...
WHERE ...

你也可以

UPDATE products p
SET p.product_price='87.00000'
WHERE EXISTS (SELECT NULL 
              FROM product_category pc
              WHERE p.product_id = pc.product_id
              AND pc.category_id = '64');

答案 1 :(得分:1)

您可以使用以下内容:

UPDATE products 
INNER JOIN product_category
  ON products.product_id = product_category.product_id 
SET products.product_price = '87.00000'
WHERE product_category.category_id = '64';

请参阅SQL Fiddle with Demo

答案 2 :(得分:1)

我认为SET子句需要在表引用之后和WHERE子句之前,如下所示:

UPDATE products
 INNER
  JOIN product_category
    ON products.product_id = product_category.product_id 
   SET products.product_price = '87.00000'
 WHERE product_category.category_id = '64'

这是我在需要UPDATE时获得该语法的方法。我总是从一个select语句开始,这让我知道哪些行将被更新。例如:

SELECT p.*, c.*
  FROM products p
  JOIN product_category c
    ON p.product_id = c.product_id 
 WHERE c.category_id = '64'

要将其转换为更新语句,我在表引用之后和SET子句之前添加“WHERE”子句,然后将“SELECT ... FROM”替换为“{ {1}}“关键字。瞧。

答案 3 :(得分:1)

UPDATE products
INNER JOIN product_category
ON products.product_id = product_category.product_id 
SET products.product_price = '87.00000'
WHERE product_category.category_id = '64'