2012-11-29 72 views
0

我在這個問題上有一個主要的大腦放屁,我希望有人可以看看這個,並給出一些線索如何做到這一點。Mysql很多很多表和查詢

我有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和位置,bookcopies和用戶,本書,書的副本之間,添加多對多表

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,並且由於在1月11日,和位於健康科學公共圖書館?

我是否設置了許多表的表?有另外一種方法我應該這樣做嗎?

+2

除了主要問題之外,我認爲模式設計並不那麼糟糕。我建議你以不同的方式存儲'book_copies'數據,並且每個副本存儲一個條目。該表格看起來像(id,book_id,copy_id)或(id,book_id) –

+1

除了James所說的外,我還建議您將日期存儲爲'DATE'類型;當您獲得大量記錄時,表格會更小,索引效率更高。 –

+0

'book_copies_locations'也有問題。使用此設置,書本可以位於多個位置。您應該爲該表添加一個'UNIQUE(bookcopid)'約束。 –

回答

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索引安裝得很好。