在我的MySQL表中添加约束以拒绝相同类型的第3次插入的最有效方法是什么?
CREATE TABLE `stack_over_t` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`data` varchar(45) NOT NULL,
`category` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
)
理想情况下,我想阻止类别为1的插入(在插入之前触发?),因为已经有两个类别为1的条目。我该怎么做?我可以将其扩展到多个列吗?
答案 0 :(得分:1)
如果您使用触发器,则有可能或者您可以设置客户端和服务器端验证。
DELIMITER $$
CREATE TRIGGER example_before_insert_allow_only_one_active
BEFORE INSERT ON stack_over_t FOR EACH ROW
BEGIN
IF (SELECT COUNT(id) FROM stack_over_t
WHERE id=NEW.id AND data=NEW.data) > 0
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Cannot add or update row: only one active row allowed per type';
END IF;
END;
$$
CREATE TRIGGER example_before_update_allow_only_one_active
BEFORE UPDATE ON stack_over_t FOR EACH ROW
BEGIN
IF (SELECT COUNT(id) FROM stack_over_t
WHERE id=NEW.id AND data=NEW.data) > 0
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Cannot add or update row: only one active row allowed per type';
END IF;
END;
$$
答案 1 :(得分:1)
DELIMITER $$
USE `database_name`$$
DROP TRIGGER /*!50032 IF EXISTS */ beforinsertblock $$
CREATE
/*!50017 DEFINER = 'root'@'localhost' */
TRIGGER beforinsertblock BEFORE INSERT ON `stack_over_t`
FOR EACH ROW BEGIN
DECLARE COUNT INT(11);
select count(*) INTO COUNT from stack_over_t WHERE category='1';
IF(COUNT>2) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'STATMENT';
END IF ;
END;
$$
DELIMITER ;
您可以阻止插入查询
答案 2 :(得分:0)
使用INSERT IGNORE命令而不是INSERT命令。 示例:
mysql>插入IGNORE INTO person_tbl(姓,名) -> VALUES('Jay','Thomas'); 查询正常,受影响1行(0.00秒)
mysql>插入IGNORE INTO person_tbl(姓,名) -> VALUES('Jay','Thomas'); 查询正常,受影响的0行(0.00秒)