Search code examples
mysqltriggersmamp

Comparing one column to another column in different tables and inputting the value into another column trigger MySQL


I have a table called membership. One column is called amount_paid and the other is called valid_membership. I have another table called m_type with a column called price. The linking clause is WHERE membership.type_id = m_type.type_id

I want a trigger before insert on the membership table to check if amount paid is >= 1/2 of price. If it is greater i want 1 to be placed in valid_membership else if it isn't true then 0 to be placed in valid_membership.

Just having a little trouble with the correct syntax, This is what i have tried already--

DELIMITER
 //
CREATE TRIGGER valid_membership
    BEFORE INSERT ON membership
    FOR EACH ROW
        BEGIN
        IF (NEW.amount_paid >= 1/2 price) THEN
    SET valid_membership = '1' ELSE '0'
    WHERE membership.type_id = m_type.type_id
  END IF;
END
//
DELIMITER ;

Solution

  • DELIMITER //
    
    CREATE TRIGGER valid_membership
    BEFORE INSERT ON membership
    FOR EACH ROW
    BEGIN
      SELECT
        price INTO @price
      FROM
        m_type
      WHERE
        type_id = NEW.type_id
        AND ... -- something missing here as linking by the type_id only is too wide, imho
      ;
    
      SET NEW.valid_membership = IF(NEW.amount_paid >= @price / 2, 1, 0);
    END
    //
    DELIMITER ;