首页 > 解决方案 > SQL 最大记录数

问题描述

所以我有下表:

 CREATE TABLE Hospital_MedicalRecord(
        recNo CHAR(5),
        patient CHAR(9),
        doctor CHAR(9),
        enteredOn DATE NOT NULL,
        diagnosis VARCHAR(50) NOT NULL,
        treatment VARCHAR(50),
        PRIMARY KEY (recNo, patient),
        FOREIGN KEY (patient) REFERENCES Hospital_Patient(NINumber),
        FOREIGN KEY (doctor) REFERENCES Hospital_Doctor(NINumber)
    );

我想做到这一点,这样一个病人的医疗记录就不会超过 65,535 条。我应该做一个新的声明还是应该在上表中实现它。如果需要,我可以张贴患者表。

标签: mysqlsqldatabasemaxdatabase-trigger

解决方案


您通常会before insert为此使用触发器,如果​​患者的记录数达到限制并尝试新的插入,则会引发错误:

delimiter //

create trigger Trg_Hospital_MedicalRecord
before insert on Hospital_MedicalRecord
for each row
begin
    if (
        select count(*) from Hospital_MedicalRecord where patient = new.patient
    ) = 65535 then
            set msg = concat('Patient ', new.patient, ' cannot have more than 65535 records');
            signal state '45000' set message_text = msg;
    end if;
end
//

delimiter ;

我假设您不应该允许patient在现有记录上更新 a 。但如果这可能发生,那么您还需要一个before update触发器(使用完全相同的代码)。


推荐阅读