[英]Update column from another table - mySQL 3.5.2
我尝试了几种方法来从另一个表更新 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 <= 4.0.4 不支持多表更新 我强烈建议将您的服务器更新到 MySQL 5.0.xx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.