我有Users
,Books
和BookUser
个表格。
UserID
和UserName
位于Users
表中。 BookID
和BookName
位于Books
表中。在BookUser
表中,它合并了BookID
和UserID
,因此此BookUser
表显示哪个用户已阅读哪本书。
我需要编写SQL查询来查找以下内容:
任何帮助都将不胜感激。
答案 0 :(得分:1)
这是您为每个要求构建查询的基本方法:
--The number of books that a user reads
select count(bu.BookID)
from BookUser bu
join Users u on bu.UserID = u.UserID
where u.UserName = 'whatever'
--The name of other users who read the same books
select distinct u2.UserName
from Users u
join BookUser bu on u.UserID = bu.UserID
join BookUser bu2 on bu.BookID = bu2.BookID and bu.UserID <> bu2.UserID
join Users u2 on bu2.UserID = u2.UserID
where u.UserName = 'pick one'
--The number of common books between users
select distinct u.UserName, u2.UserName, count(*)
from Users u
join BookUser bu on u.UserID = bu.UserID
join BookUser bu2 on bu.BookID = bu2.BookID and bu.UserID <> bu2.UserID
join Users u2 on bu2.UserID = u2.UserID
group by u.UserName, u2.UserName