Only one active for each relationship constraint

好久不见. 提交于 2019-12-11 06:14:43

问题


So i have this problem with my assignment. I have two entities: Order, Gifr_cupon. I have two tables: Orders, Gift_Cupons.

Each order can have many cupons or none. Each Cupon is bound to no or an single order. But only one cupon can be active for each order.

How to enforce this by constraint?

Heres a logical and ER view with DDL:

DLL:

CREATE TABLE gift_cupons (
cupon_id         INTEGER NOT NULL,
order_order_id   INTEGER,
active           INTEGER NOT NULL
);

ALTER TABLE gift_cupons ADD CONSTRAINT gift_cupon_pk PRIMARY KEY ( cupon_id 
);
ALTER TABLE gift_cupons ADD CHECK gift_cupon_check CHECK(active IS NULL OR ( active >= 0 AND active <=1 ) );

CREATE TABLE orders (
order_id INTEGER NOT NULL
);

ALTER TABLE orders ADD CONSTRAINT order_pk PRIMARY KEY ( order_id );

ALTER TABLE gift_cupons
ADD CONSTRAINT gift_cupon_order_fk FOREIGN KEY ( order_order_id )
    REFERENCES orders ( order_id );

回答1:


Kind of

Cupon - is bound to -> Order;
Order - has active -> Cupon;

Cupon (
Id PK,
orderId FK Order.Id,
Unique ( Id, orderId) -- any superset  of PK is unique
);

Order (
Id PK
ActiveCuponId,
(Id, ActiveCuponId) FK Cupon( OrderId, Id)
);

See fiddle https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=596b30905d02a9e5c799b16da5fff5ab




回答2:


Remove the ACTIVE column from the gift_cupons table, and replace this state by a foreign key in the orders table, as in:

CREATE TABLE gift_cupons (
cupon_id         INTEGER NOT NULL,
order_order_id   INTEGER,
);

ALTER TABLE gift_cupons ADD CONSTRAINT gift_cupon_pk PRIMARY KEY ( cupon_id 
);

CREATE TABLE orders (
order_id INTEGER NOT NULL
active_cupon INTEGER -- nullable
);

ALTER TABLE orders ADD CONSTRAINT order_pk PRIMARY KEY ( order_id );

ALTER TABLE gift_cupons
ADD CONSTRAINT gift_cupon_order_fk FOREIGN KEY ( order_order_id )
    REFERENCES orders ( order_id );

alter table orders
add constraint order_active_cupon_fk foreign key (active_cupon)
    references gift_cupons (cupon_id);


来源:https://stackoverflow.com/questions/56586988/only-one-active-for-each-relationship-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!