Mysql多表和多查询

Mysql多表和多查询,mysql,sql,Mysql,Sql,我在这个问题上有一个很大的大脑放屁,我希望有人能看看这个,并给出一些如何做的线索 我有4个表-用户、图书拷贝、图书馆位置、图书 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)

我在这个问题上有一个很大的大脑放屁,我希望有人能看看这个,并给出一些如何做的线索

我有4个表-用户、图书拷贝、图书馆位置、图书

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) );
我在图书拷贝和位置、图书拷贝和用户、图书拷贝和图书拷贝之间有很多关系,添加了多个表

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')
我该如何查询才能返回《哈利·波特》的两本,12月18日退房,1月11日到期,位于健康科学公共图书馆


我是否正确地设置了多对多表?是否有其他方法可以执行此操作?

我希望看到您的模式如下:

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)
添加您的
用户
位置
表,您应该都设置好了


正如其他人所指出的那样,做好独特索引的设置。

除了主要问题之外,我认为模式设计没有那么糟糕。我建议您以不同的方式存储
图书副本
数据,并且每个副本存储一个条目。该表看起来像(id,book\u id,copy\u id)或(id,book\u id)除了James所说的之外,我还建议您将日期存储为
DATE
类型;当您获得大量记录时,表会更小,索引效率也会更高。
book\u copies\u location
也有问题。使用此设置,书籍副本可以位于多个位置。您应该在该表中添加一个
UNIQUE(bookcopid)
约束。另外:如果(以及何时)有一本书被归还,您不会存储。@ypercube我想他会在归还时删除
borrow
行。