douhuan4699 2013-05-21 12:20 采纳率: 100%
浏览 26
已采纳

用于更新mysql数据库中所有列的脚本

Hi I am using PHP to manipulate information in my MySQL database. However I am looking for a way to update a table (all records need to be updated) based on information within another table.

For example I have a list of products lets say 10 each with a unique id stored in a products table. I have a purchases table which has the same product ID and the amount of purchases done for each product. I want to update each product in the products table to reflect the total purchases made for each product and store it in a column called instock which is part of the products table.

How can this be done?

  • 写回答

1条回答 默认 最新

  • duannan4486 2013-05-21 12:54
    关注

    If I understand your situation correctly, you're dealing with a stock-count. When an item is purchased (represented by a entry in the Products table) then the stock count figure should be decreased. This should happen within the same transaction as the new entry to the Products table to keep your data consistent. I would recommend using a Trigger on the table to implement this. You'll find lots of information about implementing triggers in MySQL on this site. A trigger you could use might look something like this:

    CREATE TRIGGER update_stock_count
        BEFORE INSERT ON Purchases
        FOR EACH ROW
        BEGIN 
            UPDATE Products SET stock_count = stock_count - NEW.quantity_ordered
                WHERE product_id = NEW.product_id;
        END;
    

    This trigger doesn't take into account that there might not be enough stock of a product, nor does it handle updates or deletes on the Purchases table but it could be modified to do so.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler