什么是用户名的SQL查询和常用书籍的数量?

时间:2018-05-24 23:32:42

标签: sql

我有UsersBooksBookUser个表格。

UserIDUserName位于Users表中。 BookIDBookName位于Books表中。在BookUser表中,它合并了BookIDUserID,因此此BookUser表显示哪个用户已阅读哪本书。

我需要编写SQL查询来查找以下内容:

  • 用户阅读的图书数量
  • 阅读相同图书的其他用户的姓名
  • 用户之间的普通书籍数量?

任何帮助都将不胜感激。

1 个答案:

答案 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