duanke1286 2019-01-22 07:55
浏览 92

将字段移动到另一个表并使用该ID更新第三个表中的行

I have three tables called "itemorders", "mycart" and "products". I am currently moving the items in mycart into itemorders table like this in my multiquery.

$query = "INSERT into itemorders 
  (itemID,itemName,itemSize,itemColour,itemPrice,quantity,orderID) 
   SELECT itemID,itemName,itemSize,itemColour,itemPrice,quantity, 
 LAST_INSERT_ID() FROM mycart WHERE email='".$email."'  ";

How do I use the itemID,itemColour and quantity from my query and use them to update the quantity field in the products table?

  • 写回答

1条回答 默认 最新

  • dongtanghuan1885 2019-01-22 08:14
    关注

    You could use an UPDATE INNER JOIN (https://dev.mysql.com/doc/refman/5.5/en/update.html) if your itemorders table also has a AUTO_INCREMENT column.

    Something like:

    UPDATE products p
    INNER JOIN itemorders i ON p.itemID = i.itemID AND p.itemColour = i.itemColour
    SET p.quantity = p.quantity - i.quantity
    WHERE i.ID = LAST_INSERT_ID()
    

    I haven't tested this and ensuring you handle the business invariants around avoiding going into negative stock counts is left as an exercise for the reader.

    P.S. Also be careful about SQL injection attacks (the way you are interpolating the email may make life harder for poor Bobby Tables. https://xkcd.com/327/), I'd recommend looking into PDO http://php.net/manual/en/pdostatement.bindvalue.php.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题