SQL 图书馆触发器
SQL library trigger
我正在尝试创建一个图书馆数据库。我想确保一次只能将一本书借给一个人。我对触发器没有经验,所以我想我可能会问你。
create table "book" (
"book_id" INTEGER not null,
"condition" VARCHAR2(50),
"isbn" VARCHAR2(50) not null,
constraint PK_BOOK primary key ("book_id")
);
create table "borrowed" (
"book_id" INTEGER not null,
"borrowed_id" INTEGER not null,
"user_id" INTEGER not null,
"date_borrowing" DATE not null,
"date_returning" DATE not null,
"returned" SMALLINT not null,
constraint PK_BORROWED primary key ("book_id", "borrowed_id")
);
属性 "returned" 只有是或没有值(1 或 0)
你不需要触发器。你借来的 table 的结构应该是这样的。注意使用虚拟列,需要Oracle 11g+:
create table borrowed (
borrowed_id INTEGER not null primary key, -- this should be set to a unique id for each row, using your preferred method
book_id INTEGER not null,
user_id INTEGER not null,
date_borrowing DATE not null,
date_returning DATE not null,
date_actualreturn DATE,
returned as (case date_actualreturn is null then 0 else 1 end)
);
然后,您希望 date_actualreturn
每本书最多有一个 NULL
值。您可以使用唯一索引或约束来执行此操作:
create table borrowed (
borrowed_id INTEGER not null primary key, -- this should be set to a unique id for each row, using your preferred method
book_id INTEGER not null,
user_id INTEGER not null,
date_borrowing DATE not null,
date_returning DATE not null,
date_actualreturn DATE,
returned as (case date_actualreturn is null then 0 else 1 end),
constraint unq_only_one_book_borrowed unique
(coalesce(date_actualreturn, date '1900-01-01'), book_id)
);
这会在列上创建一个唯一约束。如果一本书没有归还,日期看起来总是一样的——所以同一本书不能借两次。而且,瞧!没有触发器。
我正在尝试创建一个图书馆数据库。我想确保一次只能将一本书借给一个人。我对触发器没有经验,所以我想我可能会问你。
create table "book" (
"book_id" INTEGER not null,
"condition" VARCHAR2(50),
"isbn" VARCHAR2(50) not null,
constraint PK_BOOK primary key ("book_id")
);
create table "borrowed" (
"book_id" INTEGER not null,
"borrowed_id" INTEGER not null,
"user_id" INTEGER not null,
"date_borrowing" DATE not null,
"date_returning" DATE not null,
"returned" SMALLINT not null,
constraint PK_BORROWED primary key ("book_id", "borrowed_id")
);
属性 "returned" 只有是或没有值(1 或 0)
你不需要触发器。你借来的 table 的结构应该是这样的。注意使用虚拟列,需要Oracle 11g+:
create table borrowed (
borrowed_id INTEGER not null primary key, -- this should be set to a unique id for each row, using your preferred method
book_id INTEGER not null,
user_id INTEGER not null,
date_borrowing DATE not null,
date_returning DATE not null,
date_actualreturn DATE,
returned as (case date_actualreturn is null then 0 else 1 end)
);
然后,您希望 date_actualreturn
每本书最多有一个 NULL
值。您可以使用唯一索引或约束来执行此操作:
create table borrowed (
borrowed_id INTEGER not null primary key, -- this should be set to a unique id for each row, using your preferred method
book_id INTEGER not null,
user_id INTEGER not null,
date_borrowing DATE not null,
date_returning DATE not null,
date_actualreturn DATE,
returned as (case date_actualreturn is null then 0 else 1 end),
constraint unq_only_one_book_borrowed unique
(coalesce(date_actualreturn, date '1900-01-01'), book_id)
);
这会在列上创建一个唯一约束。如果一本书没有归还,日期看起来总是一样的——所以同一本书不能借两次。而且,瞧!没有触发器。