0

我的数据库中有 2 个表(实际上更多,但它们目前无关紧要)。

一张表存储状态为“已发布”或“已删除”的书籍。书籍的状态为已发布或已丢弃,具体取决于该书是否已被携带。

另一个表存储有关特定用户是否阅读过特定书籍的数据。

我想显示用户已阅读和尚未阅读的所有书籍的列表,这些书籍仍在携带。我创建了一个查询,它将连接两个表并匹配每本书,无论状态如何,都与特定用户和已读日期相匹配,如果未读则为 NULL。问题是,虽然我想显示用户尚未阅读的书籍,但我不想显示用户尚未阅读且不再携带的书籍(状态为垃圾)。

目前,我一直无法做到这一点。在 PHP 端的 foreach 循环中,我正在检查是否已阅读状态为垃圾的书,如果没有,则跳过它。我觉得这在数据库方面效率低下。

以下是我目前拥有的脚本。我想要完成的事情是否可能?它的效率会更高还是更低?谢谢您的帮助。

 SELECT 
     book.ID as actual_book_id,
     book.post_title,
     book.post_status,
     read.*
 FROM books as book
 LEFT OUTER JOIN book_club as read
     ON read.book_id = book.ID
     AND read.user_id = $userID
 WHERE book.post_type = 'book'
     AND book.post_status IN ('publish','trash')
 ORDER BY
     book.post_title ASC

假设 $userID 是与用户相关的有效整数

4

2 回答 2

1

您必须添加一些更复杂的子句,而不仅仅是您的 IN。

SELECT 
     book.ID as actual_book_id,
     book.post_title,
     book.post_status,
     read.*
 FROM books as book
 LEFT OUTER JOIN book_club as read
     ON read.book_id = book.ID
     AND read.user_id = $userID
 WHERE book.post_type = 'book'
     AND (book.post_status  = 'publish' OR
          (book.post_status = 'trash' AND read.<columnDate> IS NOT NULL))
 ORDER BY
     book.post_title ASC
于 2013-02-02T21:02:36.457 回答
0

我认为您可以尝试在 user_id 之前和之后查找书籍。这是示例:

SELECT 
     book.id as actual_book_id,
     book.post_title,
     book.post_status,
     r.*
FROM 
(
      SELECT 
           user_read.* 
      FROM book_club AS user_read 
      WHERE user_read.user_id = $userID
) AS r 
LEFT JOIN books as book ON r.book_id = book.id 
WHERE book.post_type = 'book'
     AND book.post_status IN ('publish','trash')
 ORDER BY
     book.post_title ASC

通过这种方式,您应该只显示给定 userID 的 post_status = 'publish' 或 'trash' 的书籍。

于 2013-02-02T22:12:39.270 回答