更新语句给出未知列错误

时间:2013-09-03 01:54:09

标签: mysql sql

我正在尝试根据categories_id在第二个表中是否等于90但是获得未知列错误来更新1列。

这是我的sql:

UPDATE products SET qty='20' 
WHERE products.products_id = products_to_categories.products_id AND products_to_categories.categories_id = '90'

我得到的错误是

'where子句'

中的未知列'products_to_categories.products_id'

5 个答案:

答案 0 :(得分:2)

在SQL中,您必须使用from(或updatedelete)语句引入表名。你的意思是:

UPDATE products
    SET qty = '20' 
    WHERE exists (select 1
                  from products_to_categories ptc
                  where ptc.products_id = products.products_id AND
                        ptc.categories_id = '90'
                 );

另一种方法是使用连接:

UPDATE products p join
       products_to_categories ptc
       on  ptc.products_id = products.products_id AND
           ptc.categories_id = '90'
    SET p.qty = '20';

如果有多个匹配项,则效果会更好。

答案 1 :(得分:0)

您不能在UPDATE命令中组合两个表。使用子查询。

UPDATE products SET qty='20' 
WHERE products.products_id IN (SELECT `ptc`.`products_id`
                               FROM   `products_to_categories` `ptc`
                               WHERE  `ptc`.categories_id = '90')

答案 2 :(得分:0)

您需要在连接语句中包含该表,除非表已加入,否则无法找到products_to_categories.products_id

UPDATE products a
       INNER JOIN products_to_categories b
             ON a.products_id = b.products_id
SET    a.qty = '20' 
WHERE  b.categories_id = '90'

答案 3 :(得分:0)

您可以使用mysql的multiple table syntax

UPDATE products
JOIN products_to_categories
  ON products.products_id = products_to_categories.products_id
  AND products_to_categories.categories_id = '90'
SET qty='20'

请参阅SQLFddile上查看的此查询语法。

答案 4 :(得分:0)

UPDATE products p, products_to_categories pc
SET p.qty='20' 
WHERE p.products_id = pc.products_id AND pc.categories_id = '90'

<强> FIDDLE