使用左连接进行条件筛选

时间:2013-02-04 21:23:02

标签: mysql join conditional-statements

我有一个booksusers和一个books_users表。

现在,我想要一本由我(user_id = 3)和其他用户(user_id = 18)管理的书:

SELECT *
FROM books as Book
LEFT JOIN books_users as BookUser
    ON BookUser.book_id = Book.id
WHERE
    Book.user_count = 2 AND
    BookUser.user_id = 3 AND
    BookUser.user_id = 18

问题: 由于左连接将行的结果拆分为行,因此它不会为两个用户提供一行......

3 个答案:

答案 0 :(得分:1)

我相信您想要两次加入BookUser表以获取这两个条件,并使用DISTINCT获取该书一次:

SELECT DISTINCT Book.*
FROM books as Book
LEFT JOIN books_users as BookUser1
    ON BookUser.book_id = Book.id
LEFT JOIN books_users as BookUser2
    ON BookUser.book_id = Book.id
WHERE
    Book.user_count = 2 AND
    BookUser1.user_id = 3 AND
    BookUser2.user_id = 18

答案 1 :(得分:1)

SELECT *
  FROM books as B
 INNER JOIN books_users as BU1
    ON BU1.book_id = B.id
 INNER JOIN books_users as BU2
    ON BU2.book_id = B.id
 WHERE B.user_count = 2
   AND BU1.user_id = 3
   AND BU2.user_id = 18

答案 2 :(得分:0)

我不知道user_count列。

这给出了3或18

使用的书籍
SELECT *
FROM books as Book
INNER JOIN books_users as BookUser
    ON BookUser.book_id = Book.id
WHERE
    Book.user_count = 2 AND
    BookUser.user_id IN  (3,18) 

SELECT *
FROM books as Book
INNER JOIN books_users as BookUser
    ON BookUser.book_id = Book.id
WHERE
    Book.user_count = 2 AND
    (BookUser.user_id = 3 OR BookUser.user_id = 18)

编辑:这会提供3和18使用的书籍。

SELECT book.*
FROM books as Book
INNER JOIN books_users as BookUser1
    ON BookUser1.book_id = Book.id
INNER JOIN books_users as BookUser2
    ON BookUser2.book_id = Book.id
WHERE
    Book.user_count = 2 AND
    BookUser1.user_id = 3 AND
    BookUser2.user_id = 18