将一列与不同表中的另一列进行比较并将值输入到另一列中会触发MySQL

时间:2019-03-22 12:59:47

标签: mysql triggers mamp

我有一个名为Membership的表。一列称为amount_paid,另一列称为valid_membership。我还有一个名为m_type的表,其中有一个名为price的列。链接子句是WHERE Membership.type_id = m_type.type_id

我希望在插入成员资格表之前触发一个触发器,以检查支付的金额是否> =价格的1/2。如果更大,我希望将1放置在valid_membership中,否则将0放置在valid_membership中。

使用正确的语法有点麻烦,这就是我已经尝试过的-

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 ;

1 个答案:

答案 0 :(得分:1)

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 ;