所以我的作业遇到了这个问题。 我有两个实体:Order,Gifr_cupon。 我有两个表:Orders,Gift_Cupons。
每个订单可以有很多勋章,也可以没有。每个Cupon均无订单或单订单。但是每个订单只能激活一个cupon。
如何通过约束来强制执行此操作?
在这里使用DDL进行逻辑视图和ER视图:
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 );
答案 0 :(得分:2)
种类
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)
);
请参见小提琴https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=596b30905d02a9e5c799b16da5fff5ab
答案 1 :(得分:1)
从ACTIVE
表中删除gift_cupons
列,并用orders
表中的外键替换此状态,如:
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);