2

我正在尝试根据第二个表中的 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”

4

5 回答 5

2

from在 SQL 中,您必须使用(或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';

如果有不止一个匹配,这会更好。

于 2013-09-03T01:57:19.540 回答
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')
于 2013-09-03T01:57:30.343 回答
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'
于 2013-09-03T01:57:42.657 回答
0

您可以使用 mysql 的多表语法

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上检查的此查询语法。

于 2013-09-03T01:59:09.253 回答
0
UPDATE products p, products_to_categories pc
SET p.qty='20' 
WHERE p.products_id = pc.products_id AND pc.categories_id = '90'

小提琴

于 2013-09-03T04:09:58.643 回答