在插入mysql表之前验证

vq8itlhq  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(308)

在mysql表中添加约束以拒绝相同类型的第三次插入,最有效的方法是什么?

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`)
)


理想情况下,我希望阻止category=1的insert(插入前触发?),因为已经有两个category为1的条目。我该怎么做?我可以扩展到多个列吗?

2ul0zpep

2ul0zpep1#

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 ;

您可以阻止插入查询

up9lanfz

up9lanfz2#

使用insert ignore命令而不是insert命令。例子:
mysql>insert ignore into person_tbl(姓,名)->值('jay','thomas');查询正常,1行受影响(0.00秒)
mysql>insert ignore into person_tbl(姓,名)->值('jay','thomas');查询正常,0行受影响(0.00秒)

bakd9h0s

bakd9h0s3#

如果您使用的是trigger,则可以设置客户端和服务器端验证。

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;
$$

相关问题