如果其他列具有值,则CREATE TABLE具有特定值的列

时间:2014-09-24 10:02:36

标签: sql postgresql ddl

我试图创建具有两个特定列的表。在其中一个(送货员)中有一些可能的值。第二,几乎没有可能的价值观。仅当传递者具有值' A'时才需要第二列中的值,否则它可以是(并且实际上应该是NULL)

这是我的尝试

CREATE TABLE dict_shipping_types ( 
    id bigserial NOT NULL,
    deliverer varchar(50) NOT NULL,
    gage varchar(1)
)
;
ALTER TABLE dict_shipping_types
    ADD CONSTRAINT CHK_dict_shipping_types_deliverer CHECK (deliverer IN ('CompanyA','CompanyB','CompanyC'))
    ;
ALTER TABLE dict_shipping_types
    ADD CONSTRAINT CHK_dict_shipping_types_gage_not_null 
        CHECK (
            (DELIVERER='CompanyA' AND GAGE IN ('A','B','C') AND GAGE != NULL ) OR 
            (DELIVERER!='CompanyA' AND GAGE=NULL)
        )
;
ALTER TABLE dict_shipping_types ADD CONSTRAINT PK_dict_shipping_types 
    PRIMARY KEY (id)
; 

测试查询

INSERT INTO dict_shipping_types(deliverer) VALUES('CompanyA')

INSERT INTO dict_shipping_types(deliverer,GAGE) VALUES('CompanyB','A')

INSERT INTO dict_shipping_types(deliverer,GAGE) VALUES('CompanyA','D')

所有这些都应该失败,但只有第三个失败。如何检查我可以允许NULLNOT NULL值?

1 个答案:

答案 0 :(得分:2)

您可以使用NOT NULL / IS NOT NULL代替!=NULL / =NULL

进行修复
CREATE TABLE dict_shipping_types ( 
    id bigserial NOT NULL,
    deliverer varchar(50) NOT NULL,
    gage varchar(1)
)
;

ALTER TABLE dict_shipping_types
    ADD CONSTRAINT CHK_dict_shipping_types_deliverer CHECK (deliverer IN ('CompanyA','CompanyB','CompanyC'))
    ;

ALTER TABLE dict_shipping_types
    ADD CONSTRAINT CHK_dict_shipping_types_gage_not_null 
        CHECK (
            (DELIVERER='CompanyA' AND GAGE IN ('A','B','C') AND GAGE is not NULL) or
(DELIVERER!='CompanyA' AND GAGE is NULL)
);

ALTER TABLE dict_shipping_types ADD CONSTRAINT PK_dict_shipping_types 
    PRIMARY KEY (id)
;