Search code examples
mysqlsqlstored-procedurestriggersmysql-error-1054

How to make a SQL UPDATE procedure use more than 1 table in the calculation? Doing so gives me error 1054


After I defined a trigger and its procedure, to diminish the amount of books on stock by an amount specified on a separate table (both being variable), it gives me error 1054, of an unknown column in the procedure. The code that defines the trigger and procedure is the following:

CREATE DEFINER=`root`@`localhost` TRIGGER reduce_available
AFTER INSERT ON book_customer FOR EACH ROW
UPDATE stock SET stock.current_amount = stock.current_amount-book_customer.amount;

Usually to process the type of interactions that would warrant this type of trigger instead I generate an entirely new table that records the purchases and sellings, with aditional useful data. However, in this specific case I don't have such a table, and would like to know how to work around it.


Some clarification:

  • The procedure ins't meant to update more than 1 table.
  • The trigger only triggers in one table, as it should.
  • I'm searching for a way to fix my procedure usage, not alternative solutions.

Additional information:

  • The code works when I set the "minus" value to 1, which means that the unknown table is the one that gives the error:
    UPDATE stock SET stock.current_amount = stock.current_amount-1;
    I can't simply do this because then I've got the issue of not being able to rent a customer more than 1 book at a time, due to not having a "sell" table that creates cronological dependence while in the same operation.
  • Both data values(stock.current_amount and book_customer.amount) are the same type (INT).
  • Due to this SQL program being made because of a very small assignment, neither me nor my team looked-up proper "coding design", instead relying on a self-stablished method. (Maybe this matters, I dunno)
  • The error I recieve is "1054", but if I mess around it changes between "1063" and a "11xx" I can't seem to replicate.

Edits:

  1. Solved! Rookie mistake; I used an uncomplete sintaxis without a "where" clause.
    The reason I didn't find it while searching was that I didn't know there could be more than 1 sintaxis in the first place.
  2. I forgot to say many thanks to Linoff!
  3. Improving readability of the question.

Solution

  • Do you just want to refer to new? If so, I assume you only want to update one row in stock rather than all of them. You need a where clause

    CREATE DEFINER=`root`@`localhost` TRIGGER reduce_available
    AFTER INSERT ON book_customer FOR EACH ROW
    BEGIN
        UPDATE stock s
            SET s.current_amount = s.current_amount - new.amount
            WHERE s.book_id = new.book_id;
    END;