比较sql中的表

时间:2015-05-17 20:01:04

标签: sql postgresql

enter image description here假设我有一张包含用户收藏书籍的表格。是否可以通过SQL命令检查与第一个用户共享最喜欢的书籍的其他用户?我已经考虑过分配一个变量来计算某本书出现在用户收藏书籍中的次数,并为其他用户表重复该次数,但我认为这需要花费很多时间。 编辑:在附图中,比较了用户最喜欢的音乐(书籍只是另一个例子)。假设这两个用户共同拥有最多的音乐,我将如何撰写查询来查找它们?

3 个答案:

答案 0 :(得分:1)

要获取两个用户之间共同的收藏夹数量,请使用聚合自加入:

select b1.userid as user1, b2.userid as user2, count(*) as inCommon
from favourites b1 inner join
     favourites b2 
     on b2.bookid = b1.bookid
where b1.userid <> b2.userid
group by b1.userid, b2.userid;

要获得拥有最多图书的用户,请使用rank()row_number()窗口函数:

select bb.*
from (select b1.userid as user1, b2.userid as user2, count(*) as inCommon,
             rank() over (partition by b1.userid order by count(*) desc) as seqnum
      from favourites b1 inner join
           favourites b2 
           on b2.bookid = b1.bookid
      where b1.userid <> b2.userid
      group by b1.userid, b2.userid
    ) bb
where seqnum = 1;

如果您只需要一个用户的值,那么您可以在第一个查询中使用limitorder by

select b1.userid as user1, b2.userid as user2, count(*) as inCommon
from favourites b1 inner join
     favourites b2 
     on b2.bookid = b1.bookid
where b1.userid <> b2.userid and b1.userid = 1
group by b1.userid, b2.userid
order by count(*) desc
limit 1;

答案 1 :(得分:0)

您可以使用别名将表连接到自身,您可以加入bookid以返回具有相同收藏书的用户列表。例如:

select 
b1.username,
b2.username
from favourites b1
inner join favourites b2 on b2.bookid = b1.bookid
where
b1.username <> b2.username

答案 2 :(得分:0)

如果您想与某个特定用户匹配,可以使用以下方法:

select 
   b2.username as OtherUser, -- matching user
   COUNT(b2.bookid) as OtherUserMatchesCount -- number of matches for the other user
from favourites b1
join favourites b2 
  on b1.bookid = b2.bookid -- they both like the same book
where b1.username = 'MATT' -- match against user 'MATT'
  and b1.username <> b2.username -- of course exclude 'MATT'
group by
   b2.username
order by COUNT(b2.bookid) DESC -- best matches on top
-- add LIMIT 1?