Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i create a trigger to verify if a record exists on another table?

Tags:

mysql

I am using version 5.0 of mysql.

I'm trying to create a trigger to check if one entry(name of Food) exists in the other table.

I´ve done this:

delimiter //
CREATE TRIGGER verifyExists BEFORE INSERT ON Sold
    FOR EACH ROW
    BEGIN
        IF NEW.nameF not in (
            select A.nameF
            From Available D
            where (NEW.nameF = A.nameF and NEW.nameR = A.nameR)
        )
        END IF;
    END;
//
delimiter ; 

this doesen't work, why?

like image 827
user3046650 Avatar asked Nov 30 '13 17:11

user3046650


People also ask

How do I insert a trigger into another table?

To create a trigger, we need to change the delimiter. Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1. To check if the records are inserted in both tables or not.

Can MySQL trigger be used for input data validation?

Moreover, triggers are ideal for validation because they can be executed before data is inserted or updated. Triggers can also can also prevent a database transaction from being applied while providing an error message.

Can we use trigger with select statement?

The trigger event that initiates the trigger action can be an INSERT, DELETE, UPDATE, or a SELECT statement. The MERGE statement can also be the triggering event for an UPDATE, DELETE, or INSERT trigger.

Can we create more than one trigger of same event on same table?

You can create multiple triggers for the same subject table, event, and activation time. The order in which those triggers are activated is the order in which the triggers were created.


1 Answers

You have a couple of errors:

delimiter //
CREATE TRIGGER verifyExists BEFORE INSERT ON Sold
    FOR EACH ROW
    BEGIN
        IF NEW.nameF not in (
            select A.nameF
            From Available A  -- CHANGED THE ALIAS TO A
            where (NEW.nameF = A.nameF and NEW.nameR = A.nameR)
        ) THEN -- MISSING THEN
           CALL `Insert not allowed`;

        END IF;
    END;
//
delimiter ; 

sqlfiddle demo

If you could use SIGNAL, it is the best way, but since it was only introduced in mysql 5.5, you will have to do it by other route. One way is to call a non existant function, like showed above. From this answer

like image 169
Filipe Silva Avatar answered Oct 02 '22 01:10

Filipe Silva