[英]SQL Constraint that one column value cannot be greater than another in a different table
由於將業務邏輯與數據庫結構混合在一起,這可能不是一個很好的問題,但我不是這樣決定的:
是否可以定義一個約束,以推斷一個列(表A,列X)的值不能大於通過外鍵引用的另一列(表B,列Y)的值:
TABLE_A
ID (Primary Key)
X (int value)
TABLE_B
A_ID (Foreign Key to TABLE_A)
Y (int value)
即我想對Y的所有值強制執行,Y <L,其中L是來自X的值,其中TABLE_B.A_ID == TABLE_A.ID
我正在使用DB2。
是否可以定義一個約束,以推斷一個列(表A,列X)的值不能大於通過外鍵引用的另一列(表B,列Y)的值:
否。那將需要在CHECK約束中使用SELECT語句,而DB2不支持該語句。 如果它確實支持使用SELECT語句,它將看起來像這樣。
ALTER TABLE_B
ADD CONSTRAINT TABLE_B_Y_LT_L
CHECK (Y < (SELECT X FROM TABLE_A WHERE TABLE_A.ID = TABLE_B.A_ID));
SELECT語句將返回單個值,因為TABLE_A.ID是唯一的。 但是,就像我說的那樣,DB2在檢查約束中不支持SELECT語句。 我認為當前沒有任何dbms。
解決方法
有幾種解決方法。 首先,您可以編寫一個觸發器。 其次,您可以將列“ X”存儲在兩個表中,並使用外鍵約束和檢查約束來實現您的需求。
-- Since "id" is unique, the combination of "id" and "x" is also unique.
-- Declaring "unique (id, x)" lets these two columns be the target of a
-- foreign key reference.
--
create table table_a (
id integer primary key,
x integer not null,
unique (id, x)
);
-- The foreign key references both columns in "table_a". The check constraint
-- indirectly guarantees that y < table_a.x.
--
create table table_b (
a_id integer not null,
a_x integer not null,
y integer not null,
primary key (a_id, a_x, y),
foreign key (a_id, a_x) references table_a (id, x),
check (y < a_x)
);
這是標准的SQL。 它應該可以在任何當前的SQL dbms中使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.