你可以做到這一點:
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
來源
2016-06-07 20:15:05
MT0
你不能。不是一個約束。你可以創建一個函數/過程來做到這一點。無法創建約束來檢查以前的行。一個函數會爲你服務嗎? –