我尝试过几种方法从另一个表更新mySQL数据库表中的列但是没有运气。

我在某处读到版本3.5.2不支持多表更新,我需要一个基于代码的解决方案 - 这是正确的吗?

如果没有,任何人都可以使用sql指向正确的方向吗?

UPDATE products SET products_ordered = (
    SELECT SUM(products_quantity) 
    FROM orders_products 
    WHERE products_id = products.products_id
);

或:

Create temporary table my_temp_table
as
SELECT products_id, SUM(products_quantity) as total 
FROM orders_products 
GROUP BY products_id 

UPDATE products, my_temp_table
SET products.products_ordered = my_temp_table.total 
WHERE products.products_id = my_temp_table.products_id
有帮助吗?

解决方案

当我以前使用不支持子查询或多表更新的MySQL时,我使用了一个技巧来完成你所描述的内容。运行查询,其结果本身就是SQL语句,然后保存输出并将其作为SQL脚本运行。

SELECT CONCAT( 
  'UPDATE products SET products_ordered = ', 
   SUM(products_quantity), 
  ' WHERE product_id = ', products_id, ';') AS sql_statement
FROM orders_products
GROUP BY products_id;

顺便说一句,据我所知,没有MySQL 3.5.x这样的版本。我想你可能报错了。否则你正在使用其他产品,如mSQL。

编辑:我忘了在上面的查询生成的SQL语句中添加分号。

其他提示

MySQL <!> lt; = 4.0.4不支持多表更新 我强烈建议您将服务器更新到MySQL 5.0.xx

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top