[英]How to write SQL query for these 5 tables?
I am writing an application that helps book exchange between users. 我正在编写一个可帮助用户之间进行书本交换的应用程序。 I am using PHP and MySQL, and I am pretty new to them both. 我正在使用PHP和MySQL,对它们两者来说我都是新手。
I have 5 tables, 3 data tables and 2 service tables: 我有5个表,3个数据表和2个服务表:
user: with user attributes (user_id, name, birth... etc). 用户:具有用户属性(user_id,名称,出生等)。
book: with book attributes (book_id, name, author, publisher... etc). book:具有书籍属性(book_id,名称,作者,出版商等)。
copy: represents actual copies of a books (copy_id, condition, comments... etc). 复制:代表书籍的实际副本(copy_id,条件,注释等)。
user_copy: describes which user holds which copy, composed out of userID and copyID. user_copy:描述哪个用户持有哪个副本,由userID和copyID组成。
copy_book: represents the connection of copy and book, composed out of copyID and bookID copy_book:代表copy和book的连接,由copyID和bookID组成
My question is: what is the easiest and most efficient statement for getting the book attributes and copy attributes for each copy that a user holds? 我的问题是:对于用户持有的每个副本,获取书本属性和副本属性的最简单,最有效的方法是什么?
You need to inner join all the tables that you are interested in: book, copy, user_copy, and copy_book. 您需要内部联接所有您感兴趣的表:book,copy,user_copy和copy_book。 The SELECT statement that returns attributes on all copies held by a user may look like this: 返回用户持有的所有副本上的属性的SELECT语句可能看起来像这样:
SELECT B.bookID
, B.name
, B.author
, B.publisher
, C.condition
, C.comments
-- you may get other fields that you are interested in here..
FROM book B
INNER JOIN copy_book CB ON B.bookID = CB.bookID
INNER JOIN user_copy UC ON UC.copyID = CB.copyID
INNER JOIN copy C ON C.copyID = UC.copyID
WHERE UC.userID = <the user Id that you want>
I hope it's pretty clear what the statement does but if you have any questions, please ask. 我希望声明很清楚,但是如果您有任何疑问,请询问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.