SQL最大记录数

时间:2019-12-10 16:28:19

标签: mysql sql database max

所以我有下表:

 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个。我应该发表新的声明还是应该在上表中执行它?如果需要的话,我可以张贴病人表。

2 个答案:

答案 0 :(得分:2)

您通常会为此使用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。但是,如果这可能发生,那么您还需要一个before update触发器(具有完全相同的代码)。

答案 1 :(得分:1)

请考虑以下内容...

 DROP TABLE IF EXISTS my_table;

 CREATE TABLE my_table(id SERIAL PRIMARY KEY, user_id INT NOT NULL);

 INSERT INTO my_table (user_id)
SELECT 1
  FROM (SELECT 1) x
  LEFT
  JOIN (SELECT user_id FROM my_table GROUP BY user_id HAVING COUNT(*) >=3) y
    ON y.user_id = 1
 WHERE y.user_id IS NULL
 LIMIT 1;

这会将每个用户ID的插入限制为3个。