SQL约束,一个列值不能大于另一个表中的另一个列值

时间:2013-04-25 09:59:04

标签: sql db2 constraints check-constraint

这可能不是一个非常好的问题,因为它将业务逻辑与DB结构混合,但它不是我的决定所以:

是否可以定义约束,推断一列的值(表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< Y的所有值。 L其中L是来自X的值,其中TABLE_B.A_ID == TABLE_A.ID

我正在使用DB2。

1 个答案:

答案 0 :(得分:2)

  

是否可以定义约束,推断一列的值(表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。