Mysql很多很多表和查询

时间:2012-11-29 16:26:34

标签: mysql sql

我对这个问题有一个重要的脑屁,我希望有人可以看看这个,并提供一些线索,如何做到这一点。

我有4个表 - 用户,book_copies,图书馆位置,图书。

Create table book 
( id int not null auto incre, 
  name varchar(55), 
primary key(id) );

Create table book_copies 
( id int not null auto incre, 
  number of copies), 
primary key(id) );

Create table location 
( id int not null auto incre, 
  address varchar(55), 
primary key(id) );

Create table users 
( id int not null auto incre, 
  name varchar(55), 
primary key(id) );

我在book_copies和地点,书籍和用户,书籍和书籍副本之间有许多关系,并添加了许多表

Create book_copies_locations 
( locationid int (11) not null, 
  bookcopyid int (11) not null, 
primary key(locationid,bookecopyid) , 
foreign key (locationid) references locations.id, 
foreign key (bookcopyid) references book_copies.id) );

Create table borrow 
( userid int (11) not null, 
  bookcopyid int (11) not null, 
  checkoutdate varchar(55), 
  duedate varchar(55), 
primary key(userid,bookecopyid) , 
foreign key (userid) references users.id, 
foreign key (bookcopyid) references book_copies.id) );

Create table book_copies_books 
( booksid int (11) not null, 
  bookcopyid int (11) not null, 
  checkoutdate varchar(55), 
  duedate varchar(55), 
primary key(booksid,bookecopyid) , 
foreign key (booksid) references books.id, 
foreign key (bookcopyid) references book_copies.id) );

我想要做的是跟踪每本书的副本,并告诉它在哪个位置?,用户检查了什么?以及什么日期?

我添加了类似

的内容
insert into borrow (userid,bookcopyid, checkoutdate, duedate) values( '1', '1', 'dec 18', 'jan 11')

insert into users (id,name) values( '1', 'bob')

insert into book_copies (id,number_of_copies) values( '2', '33')

insert into books (id,name) values( '1', 'harry potter')

insert into locations (id,address) values( '1', 'health science public library')

我将如何回答有2个哈利波特的副本,于12月18日检查并于11月1日到期,并且位于健康科学公共图书馆?

我是否使用多对多表格设置表格?我还有另一种方法吗?

1 个答案:

答案 0 :(得分:0)

我宁愿看到这样的架构:

book (id, name)
book_copy (id, location_id, book_id, status)

请注意,要计算给定图书的副本,请查看book_copy。在您的示例中,book_id = 1将有两行。

status将是非规范化值,以防止您从结帐历史中确定最新状态。

然后用户查看该书的副本:

book_checkout (id, user_id, book_copy_id, checkout_date, due_date)

添加您的userlocation表格,您应该全部设置。

正如其他人所指出的那样,让你的UNIQUE索引设置得很好。