简体   繁体   中英

Update trigger MySQL giving syntax error

I want to create trigger to make update on table when inserting rows to other table, but I get a syntax error for this:

CREATE TRIGGER quantity AFTER INSERT ON sale_items
FOR EACH ROW
BEGIN
update products set quantity = quantity -1 where id =(
SELECT product_id
FROM sale_items
ORDER BY id desc
LIMIT 1)
END;

Error:

# 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 7

This seems like a silly trigger. Why are you fetching the last update id using a subquery? It should be available through new :

DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
    FOR EACH ROW
    BEGIN
    update products
        set quantity = quantity - 1
        where id = new.product_id
    END//
DELIMITER ;

Use proper Delimiter in your trigger , the correct code is:

DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
    FOR EACH ROW
    BEGIN
    update products set quantity = quantity - 1
        where id = new.product_id ;
    END//
DELIMITER ;

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