0

我有一个books,users和一张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

问题:当左连接将书籍的结果分成几行时,它不会给两个用户一行...

4

3 回答 3

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
于 2013-02-04T21:28:27.470 回答
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
于 2013-02-04T21:28:52.647 回答
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
于 2013-02-04T21:30:50.157 回答