SQL - 返回用户拥有的书籍

时间:2018-01-23 19:04:36

标签: php mysql sql database relational-database

我在我的大学项目中执行查询时遇到了一些问题。我有一个网站,用户可以分享他们阅读的书籍,我有一个页面,用户可以查看他添加的书籍(他拥有的书籍)。

为此我相信我需要记录用户的id,我存储在会话PHP变量中,用户id在表用户中。 有关这些书籍的信息存储在一本书籍表中,它有自己的id主键。 然后,显示谁拥有我拥有的表owns_book(id,u_id,book_id)。

现在进行测试我总共得到了26本书,其中25本是由身份为57的用户和1位用户身份为49的书籍添加的。 当我运行此查询时:

SELECT id, title, author, category, cover, added, user_id FROM books, users 
WHERE user_id=49 AND id IN(SELECT book_id FROM owns_book) 
AND user_id IN(SELECT u_id FROM owns_book)

结果很糟糕,我没有得到预期的一本书,我也得到了其他用户添加的书籍。 有人可以告诉我我需要的正确查询,或者我是否需要更改表格的结构?感谢。

编辑:

users(user_id, ...) 
books(id, title, author, publisher, published, cover... ) 
owns_book(id, u_id, book_id)

3 个答案:

答案 0 :(得分:2)

It looks like you're looking to to grab everything from your books table that is owned by a specific customer. If that's the case, you can try

SELECT * FROM books 
JOIN owns_book 
ON books.id = owns_books.book_id 
WHERE owns_book.user_id = 49 

This will select all of the props from your books table then joins the tables based on on the ID of the book being equal to the book_id of the owns_book. Lastly, add the parameter - you only want to see user_id = 49.

答案 1 :(得分:1)

您可以简化此查询并使用LEFT JOIN ...

SELECT books.id, title, author, category, cover, added, users.user_id 
    FROM users 
    LEFT JOIN owns_book on owns_book.user_id = users.user_id
    LEFT JOIN books on books.id = owns_book.id
    WHERE users.user_id=49

这将链接user_id并列出此user_id拥有的所有书籍(JOIN的ON位)。 WHERE子句仅限于列出您之后的user_id的记录。

如果在列的主列表中,多个表上有一列(如user_id),则在其前面加上表名,以允许数据库检测您要使用的列(即使它们可能是相同的值)。

答案 2 :(得分:0)

You could also use inner join to join the tables users and books with the owns_book table:

SELECT id, title, author, category, cover, added, user_id 
    FROM owns_book 
    INNER JOIN users ON users.id = owns_book.u_id
    INNER JOIN books ON books.id = owns_book.book_id
    WHERE users.user_id=49