MySQL触发器-限制存储在列中的值的数量

时间:2018-10-25 21:23:30

标签: mysql triggers

数据库名称:库

Clients table: 
ID_number | Surname | Forename ...

Loans table: 
Loan_ID | Borrower | Book | Date

客户ID_Number是Loans.Borrower

中的外键

我想将每个客户的贷款额限制为<= 5

因此,如果在“借方”列中,ID_Number重复> 5次,则不会插入。

我如何使用TRIGGER来实现呢?

到目前为止,我有:

CREATE TRIGGER limit_borrows BEFORE INSERT

ON Loans

FOR EACH ROW

BEGIN

[NO IDEA WHAT GOES HERE]

IF value in borrow column repeated > 5 
Do not insert

[NO IDEA WHAT GOES HERE]



END IF;

END // 

2 个答案:

答案 0 :(得分:0)

这是一个主意...

DROP TABLE IF EXISTS loans;

CREATE TABLE loans
(loan_id SERIAL PRIMARY KEY
,user_id INT NOT NULL
);
INSERT INTO loans (user_id) 
SELECT 128 
  FROM (SELECT 1) x 
  LEFT 
  JOIN 
     ( SELECT user_id
            , COUNT(*) total 
         FROM loans 
        GROUP  
           BY user_id
     )  y 
    ON y.user_id = 128
   AND y.total >= 5
 WHERE y.user_id IS NULL;

答案 1 :(得分:0)

您需要计算if语句中id的数量并触发错误,以便不插入该行:

CREATE TRIGGER limit_borrows BEFORE INSERT

ON Loans

FOR EACH ROW

BEGIN
DECLARE _id (borrower id data type here)

SELECT borrower from loans where loan_ID = new.loan_ID into _id;

SET @count = (select count(1) from loans where borrower_id = _id ;
IF @count > 5
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'your error message';

END IF;

END //