MySQL通过多对多的关系统计用户之间的共同点

时间:2012-06-06 17:02:04

标签: mysql

我有一个包含3个表的MySQL数据库:users,posts和users_posts。 users-posts关系是多对多的。如何获得所有帖子对的列表以及他们共有多少用户?它基本上给了我一个帖子列表以及有多少用户评论了它们。关键是要准备好数据导入网络分析软件。结果列表在网络术语中称为“边缘列表”,共同的用户是边缘权重。

架构:

users
id
name

posts
id
title
body

users_posts
user_id
post_id

期望的输出:

postname1         postname2     users_in_common
Here's a title    Title #2      2
Another post      Title #2      11

我尝试过搜索,但在多对多,加入,三张桌子,数量,对,共享等方面甚至都不知道正确的搜索字词。感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

我的查询会生成所有帖子对,包括没有普通用户的帖子(在这种情况下,0中会有users_in_common)。在SQL Fiddle上尝试我的解决方案或查看代码:

select
    p1.title as postname1,
    p2.title as postname2,
    coalesce(s.users_in_common, 0) as users_in_common
from posts p1
    inner join posts p2 on p1.id < p2.id
    left join (
        select
            up1.post_id as post1_id,
            up2.post_id as post2_id,
            count(*) as users_in_common
        from users_posts up1, users_posts up2
        where up1.user_id = up2.user_id
            and up1.post_id < up2.post_id
        group by up1.post_id, up2.post_id
    ) s
    on (s.post1_id = p1.id and s.post2_id = p2.id)
order by p1.id, p2.id;

答案 1 :(得分:0)

试试这个

select
  p1.title as postname1,
  p2.title as postname2,
  (select count(*) from user_posts up where up.post_id in (p1.post_id, p2.post_id) as users_in_common
from
  posts p1, posts p2