需要你的帮助
我在Oracle SQL Developer中有一个这样的表:
Issue ID|Subscriber_ID|Book_ID| Taken |Returned --+-------------+-------+--------+-------- 1 | 1 | 2 |01-06-16|05-06-16 2 | 3 | 5 |07-05-16| (null) 3 | 2 | 2 |06-06-16| (null) 4 | 1 | 3 |17-05-16|26-05-16
这是某种类型的图书馆书籍,其中返回列中的(null)表示此书尚未返回。我需要创建验证规则以避免发出未返回的书籍(例如我目前无法读取#5书)。我该如何实施呢?
答案 0 :(得分:1)
嗯。您不能使用check
约束来执行此操作,因为这些约束仅适用于一行中的值。
您要确保的是,您没有两本书的返回值。有些数据库支持过滤的唯一索引:
create unique index on unq_issue_bookid on issue(book_id) where returned is null;
但不是甲骨文。您可以使用基于函数的索引执行非常类似的操作:
create unique index on unq_issue_bookid_returned
on issue(book_id,
(case when returned is not null then id else -1 end)
);
这与每本书只允许一个NULL
值具有相同的效果。
答案 1 :(得分:0)
你可以用:
CREATE TABLE table_name ( ID, Subscriber_ID, Book_ID, Taken, Returned ) AS
SELECT 1, 1, 2, DATE '2016-06-01', DATE '2016-06-05' FROM DUAL UNION ALL
SELECT 2, 3, 5, DATE '2016-05-07', NULL FROM DUAL UNION ALL
SELECT 3, 2, 2, DATE '2016-06-06', NULL FROM DUAL UNION ALL
SELECT 4, 1, 3, DATE '2016-05-17', DATE '2016-05-26' FROM DUAL;
ALTER TABLE table_name ADD is_borrowed
GENERATED ALWAYS AS ( CASE WHEN returned IS NULL THEN 1 END ) VIRTUAL;
ALTER TABLE TABLE_NAME ADD CONSTRAINT is_borrowed__u
UNIQUE( book_id, is_borrowed );
然后:
INSERT INTO table_name ( ID, Subscriber_ID, Book_ID, Taken )
VALUES ( 5, 2, 5, DATE '2016-06-06' );
将失败:
SQL Error: ORA-00001: unique constraint (TEST.IS_BORROWED__U) violated