0

您好,这是我的结构tbl_patient

CREATE TABLE tbl_patient
(
    id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    idPatient varchar(15) DEFAULT NULL,
    namePatient varchar(40) NOT NULL,
    age int NOT NULL,
    birthDate date,
    gender varchar(15) NOT NULL,
    status varchar(15) NOT NULL,
    address varchar(255) NOT NULL,
    work varchar(25) NOT NULL,
    phone varchar(15) NOT NULL
)
ENGINE=InnoDb;

我想把 2 个触发器放在tbl_patient

CREATE TRIGGER patientTrigger
BEFORE INSERT ON tbl_patient
FOR EACH ROW
SET NEW.idPatient = CONCAT("PAS-",COALESCE((SELECT MAX(id)+1 from tbl_patient),1));

CREATE TRIGGER ageTrigger
BEFORE INSERT ON tbl_pasien
FOR EACH ROW
SET NEW.age = YEAR(CURDATE()) - YEAR(birthDate);

但是我遇到了一些错误:

1235 - 此版本的 MariaDB 尚不支持“一个表具有相同操作时间和事件的多个触发器”

如何在我的桌子上实现这 2 个触发器?

4

2 回答 2

1

您可以改用计算列

CREATE TABLE tbl_patient
(
    id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    idPatient varchar(15) AS (CONCAT("PAS-", id)),
    namePatient varchar(40) NOT NULL,
    age int AS (YEAR(CURDATE()) - YEAR(birthDate)),
    birthDate date,
    gender varchar(15) NOT NULL,
    status varchar(15) NOT NULL,
    address varchar(255) NOT NULL,
    work varchar(25) NOT NULL,
    phone varchar(15) NOT NULL
)
ENGINE=InnoDb;

评论:

1)请注意,您计算年龄的代码不正确,例如(2015-12-31 和 2016-01-01)。

计算年龄的更好方法:

SELECT YEAR(NOW()) - YEAR(birthDate) - 
       (DATE_FORMAT(birthDate, '%m%d') > DATE_FORMAT(NOW(), '%m%d')) AS age

2)

CREATE TRIGGER patientTrigger
BEFORE INSERT ON tbl_patient
FOR EACH ROW
SET NEW.idPatient = CONCAT("PAS-",COALESCE((SELECT MAX(id)+1 from tbl_patient),1));

当发生多个并发 INSERT 时,这是一个糟糕的解决方案。


编辑

在用户更新时使用触发器更新年龄birthDate(是的,它可能会发生)。

其他可能的解决方案是简单地创建视图。

CREATE VIEW vw_patient
AS 
SELECT `id`,  `namePatient`, `birthDate`,
       `gender`, `status`, `address`, `work`, `phone`,
  CONCAT("PAS-", id) AS `idPatient`,
  YEAR(NOW()) - YEAR(birthDate) - 
       (DATE_FORMAT(birthDate, '%m%d') > DATE_FORMAT(NOW(), '%m%d')) AS `age`
FROM `tbl_patient`

SqlFiddleDemo

于 2015-12-27T11:12:21.207 回答
0

尝试将两个触发器的主体合并为一个,如下所示:

CREATE TRIGGER patientTrigger BEFORE INSERT ON tbl_patient FOR EACH ROW 
BEGIN
    SET NEW.idPatient =  CONCAT("PAS-",COALESCE((SELECT MAX(id)+1 from tbl_patient),1)); 
    SET NEW.age = YEAR(CURDATE()) - YEAR(birthDate);
END
于 2015-12-27T11:12:17.567 回答