选择pivvot有两个记录的位置

问题描述 投票:0回答:1

Sqlite 3.22.0

我有这些表:usersbookuser_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

但得到了空洞的结果。

sqlite
1个回答
1
投票

您必须加入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
© www.soinside.com 2019 - 2024. All rights reserved.