一个表具有三行:analysisId(整数,AUTO_INCREMENT),dataId(整数,另一个表的外键),first_attempt(布尔)
我有一个触发器,它应该是检查整个表的约束,如果存在first_attempt为1的“ dataId”,
那么您就无法添加first_attempt为'1'的另一个dataId。但是,如果以前使用了dataId,并且first_attempt为0,则它​​应接受任意数量的条目。

我已经写了一个触发器,但是mysql不断抛出语法错误,我不确定是什么问题。

这是我的桌子:

CREATE TABLE table1 (
    dataId int NOT NULL AUTO_INCREMENT,
    machine char(20) NOT NULL,
    run char(25) NOT NULL,
    PRIMARY KEY (dataId)
) ENGINE=INNODB;


CREATE TABLE table2 (
    analysisId int NOT NULL AUTO_INCREMENT,
    dataId int NOT NULL,
    first_attempt boolean,
    PRIMARY KEY (analysisId),
    FOREIGN KEY (dataId)
        REFERENCES seq_data(dataId)
        ON DELETE CASCADE
) ENGINE=INNODB;


用伪值填充数据:

INSERT INTO `table1` (`dataId`, `machine`, `run`) VALUES (DEFAULT, 'mac1', 'first_run');
INSERT INTO `table2` (`analysisId`, `dataId`, `clinical`) VALUES (DEFAULT, 1, 1);


DELIMITER $$
CREATE TRIGGER `insert_trigger` BEFORE INSERT ON `clinical_gatekeeper`
    FOR EACH ROW
    BEGIN
        IF (NEW.dataId = table2.dataId ) THEN
            SELECT CONCAT(NEW.dataId, " has already completed one successful run!") INTO @error_text;
            SIGNAL SQLSTATE "45000" SET message_text = @error_text;
        END IF;
    END;$$
DELIMITER ;


我个人认为IF (NEW.dataId = table2.dataId ) THEN有问题,因为如果我用table2.dataId替换为1,它将起作用!

最佳答案

DELIMITER $$
CREATE TRIGGER `insert_trigger` BEFORE INSERT ON `table2`
    FOR EACH ROW
    BEGIN
        IF EXISTS(SELECT 1 FROM table2 WHERE dataId = NEW.dataId AND clinical = NEW.clinical AND clinical = 1) THEN
            SELECT CONCAT(NEW.dataId, " has already completed one successful run!") INTO @error_text;
            SIGNAL SQLSTATE "45000" SET message_text = @error_text;
        END IF;
    END;$$
DELIMITER ;

09-20 09:25