如何使一列与同一表中的另一列相关

时间:2019-07-26 02:15:05

标签: sql postgresql

我正在创建一个新的数据库表,我想使一列依赖于另一列。

我尝试添加一些检查约束


CREATE TABLE borrower (
   borrower_salary_id INT REFERENCES borrower_salary(id),
   borrower_additional_income BOOLEAN NOT NULL,
   borrower_additional_income_amount INT,
   borrower_previous_loans BOOLEAN NOT NULL,
   borrower_previous_loans_payment_delay BOOLEAN,
);

当且仅当orrower_additional_income为真时,borower_additional_income_amount应该包含一些值我该怎么做?

1 个答案:

答案 0 :(得分:2)

check约束如下:

CREATE TABLE borrower (
   borrower_salary_id INT REFERENCES borrower_salary(id),
   borrower_additional_income BOOLEAN NOT NULL,
   borrower_additional_income_amount INT,
   borrower_previous_loans BOOLEAN NOT NULL,
   borrower_previous_loans_payment_delay BOOLEAN,
   CHECK ( (borrower_additional_income AND  borrower_additional_income_amount IS NOT NULL) OR
           (NOT borrower_additional_income AND borrower_additional_income_amount IS NULL )
         )
);

或简化为:

   CHECK ( borrower_additional_income =  (borrower_additional_income_amount IS NOT NULL)
         )
);

问题是,为什么要有一个标志?为什么不只检查borrower_additional_income_amount是否为NULL