MySQL触发用于限制条目号?

时间:2017-10-30 12:24:47

标签: mysql triggers

我有一张桌子产品

CREATE TABLE `products` (
  `transactionnumber` int(11) NOT NULL AUTO_INCREMENT,
  `customerID` mediumint(6) unsigned zerofill NOT NULL,
  `product` varchar(100) NOT NULL,
  `datebought` date NOT NULL,
  PRIMARY KEY (`transactionnumber`),
  UNIQUE KEY `product_unique` (`customerID`,`product`,`datebought`),
  UNIQUE KEY `product_unipr` (`customerID`,`product`),
  KEY `product` (`product`),
  CONSTRAINT `prod_ibfk_1` FOREIGN KEY (`customerID`) REFERENCES `custdetails` (`ID`),
  CONSTRAINT `prod_ibfk_2` FOREIGN KEY (`product`) REFERENCES `product catalogue` (`Itemdescription`)
) ENGINE=InnoDB AUTO_INCREMENT=63 DEFAULT CHARSET=latin1 |

我正在尝试添加一个触发器,如果​​customerID已与10个产品相关联,则会阻止任何人插入任何产品。

我试着写这样的东西

Delimiter ^^
CREATE TRIGGER maxfiveproducts BEFORE INSERT on Products 
FOR EACH ROW BEGIN
if ((SELECT CustomerID, Count(*) from products GROUP BY CustomerID)>10) then
signal allstate '45000' SET MESSAGE_TEXT = 'No more than 10 products per customer!';
end if;
end
^^
Delimiter ;

我知道我的代码可能不好,因为我刚开始学习触发器,无法在任何地方找到这个具体的例子

2 个答案:

答案 0 :(得分:3)

看起来更像是这样:

[program:worker_push_notif]
directory = /opt/initproject/workers
command = /usr/bin/php /opt/initproject/workers/fcm_pushnotif.php
autostart=true
autorestart=true
startretries=3
stdout_logfile  = /var/log/initproject/pushnotif.log
stderr_logfile  = /var/log/initproject/pushnotif.err

为什么名称为“maxfiveproducts”?

答案 1 :(得分:0)

您可以使用DECLARE声明变量,将COUNT存储在其中并编写IF条件,例如:

CREATE TRIGGER pgl_new_user 
BEFORE INSERT ON Products FOR EACH ROW
BEGIN
    DECLARE existing_products integer;

    SET @existing_products := (SELECT COUNT(*) FROM Products WHERE customerID = NEW.customerID);

    IF(@existing_products >= 10) THEN
        SIGNAL ALLSTATE '45000' SET MESSAGE_TEXT = 'No more than 10 products per customer!';
    END IF;    

END//