简体   繁体   中英

How to update multiple rows in MySQL database at once

I am having trouble with MySQL update statement. I am working in a Node/Express back end. I want to update the InventoryQTY column in the BOOK table to the value of the current value minus the value that the user has in their cart upon checkout (basically updating my inventory when a user purchases a book). The other qualification is that the update should occur for each book that is in the current user's shopping cart. Here is my query:

` UPDATE BOOK
  SET InventoryQTY =(BOOK.InventoryQTY - (SELECT Quantity FROM SHOPPING_CART_ITEM)) 
  WHERE BOOK.BookID IN 
 (SELECT BookID FROM SHOPPING_CART_ITEM WHERE CartID IN
 (SELECT CartID FROM SHOPPING_CART WHERE CustomerID = '${userID}'))`;

My current error says this: 'Subquery returns more than 1 row'. My first thought was that the query was returning multiple books since the user had three books in their cart. To test, I removed two of the books and I'm still getting the error. So the error is not because the subquery is returning multiple book IDs. I also researched that error and found that you can't use = for a query returning multiple rows; however, I am using IN so that's not the trouble either. Please help! I am perplexed!!!!

EDIT*** I slightly changed my Query:

` UPDATE BOOK
  SET InventoryQTY =(BOOK.InventoryQTY - (SELECT Quantity FROM SHOPPING_CART_ITEM WHERE CartID IN (SELECT CartID FROM SHOPPING_CART WHERE CustomerID = '${userID}'))) 
  WHERE BOOK.BookID IN 
 (SELECT BookID FROM SHOPPING_CART_ITEM WHERE CartID IN
 (SELECT CartID FROM SHOPPING_CART WHERE CustomerID = '${userID}'))`;

This takes away the error if the user has only one book in their cart. However, I get the same 'Subquery returns more than 1 row' error if there is more than one book in the cart. I now believe the error is occurring because the subquery is returning multiple book IDs. How can I resolve this?

 UPDATE Book SET UPDATE table_users SET InventoryQty = (case when user_role = 'student' then '622057' when user_role = 'assistant' then '2913659' when user_role = 'admin' then '6160230' end), date = '12082014' WHERE user_role in ('student', 'assistant', 'admin') AND cod_office = '17389551';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM