0

我有一个带有 3 个表的 MySQL 数据库: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

我尝试了搜索,但在多对多、连接、三张表、计数、配对、共享等中什至不知道正确的搜索词。感谢您的帮助!

4

2 回答 2

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;
于 2012-06-06T17:36:05.963 回答
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
于 2012-06-06T17:20:10.810 回答