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
但结果为空。
答案 0 :(得分:1)
您必须加入两个表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