Sqlite 3.22.0
我有这些表:users
,book
,user_books
。我正在尝试选择一本仅属于某些用户的书籍(下例中ID为3和5的用户):
select * from books
inner join user_books ub on books.id = ub.book_id
where ub.user_id in (3, 5)
user_books
数据:
user_id | book_id
1 | 1
2 | 2
3 | 3
4 | 4
5 | 5
3 | 5
我希望得到id为5的书,但是我得到了id为3和5的书。
怎么了?
我试过了
select * from books
inner join user_books ub on books.id = ub.book_id
where ub.user_id = 3 and ub.user_id = 5
但得到了空洞的结果。
您必须加入2个表group by b.id
并使用having count(*) = 2
,这样您才能获得属于这两个用户的书籍:
select b.id
from books b inner join user_books u
on u.book_id = b.id
where u.user_id in (3, 5)
group by b.id
having count(*) = 2