我已经尝试了几种方法来从另一个表更新 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 - 从另一个表更新列 - mySQL 3.5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/200430/