我正在创建一个新的数据库表,我想使一列依赖于另一列。
我尝试添加一些检查约束
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应该包含一些值我该怎么做?
答案 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
?