从另一个表更新列 - mySQL 3.5.2

问题描述:

我试过了几种方法来从另一个表更新mySQL数据库表中的列,但没有任何运气。从另一个表更新列 - mySQL 3.5.2

我在某处读到版本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 
+0

顺便说一句,你确定你的版本正确吗? – Node 2008-10-14 09:08:38

当我用于使用不支持子查询或多表更新的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 <支持= 4.0.4 我会极力推荐给您的服务器更新到MySQL 5.0.xx