MYSQL在插入订单时触发插入另一个表的通知

时间:2016-04-07 14:53:29

标签: mysql triggers

我有一个名为Order的表,当一个订单插入其中时,我希望它插入sellerID(通知中的userID)和productName以及要存储在Notification.Message中的消息。

CREATE TABLE `Order` (
 `OrderID` int(11) NOT NULL AUTO_INCREMENT,
`productID` int(11) NOT NULL,
`productName` varchar(255) DEFAULT NULL,
`productPrice` int(11) DEFAULT NULL,
`SellerID` int(11) DEFAULT NULL,
`BuyerID` int(11) DEFAULT NULL,
`DateSold` varchar(45) DEFAULT NULL,
PRIMARY KEY (`OrderID`),

 );


CREATE TABLE `Notifications` (
`NotificationID` int(11) NOT NULL AUTO_INCREMENT,
`userID` int(10) NOT NULL,
`Message` varchar(255) DEFAULT NULL,
`Viewed` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`NotificationID`);

他们是我的两张桌子 这就是我的尝试:

DELIMITER $$

CREATE TRIGGER productTrigger
AFTER INSERT
ON Order FOR EACH ROW

 BEGIN
 DECLARE ui,pn VARCHAR(50);

 SELECT productName INTO pn FROM Order;
 SELECT userID INTO ui FROM Product;
 INSERT INTO Notifications(userID,Message) VALUES(ui,pn);

end $$

DELIMITER ;

1 个答案:

答案 0 :(得分:1)

尝试:

DELIMITER $$

CREATE TRIGGER `productTrigger` AFTER INSERT ON `Order`
FOR EACH ROW
BEGIN
  /*DECLARE ui,pn VARCHAR(50);

  SELECT productName INTO pn FROM Order;
  SELECT userID INTO ui FROM Product;
  INSERT INTO Notifications(userID,Message) VALUES(ui,pn);*/

  INSERT INTO `Notifications`
    (`userID`, `Message`)
  VALUES
    (NEW.`SellerID`, NEW.`productName`);
END$$

DELIMITER ;