MySQL count users in common between pairs of posts through many to many relationship -


i have mysql database 3 tables: users, posts, , users_posts. users-posts relationship many-to-many. how can list of pairs of posts , how many users have in common? gives me list of posts , how many users have commented on both. point have data ready import network analysis software. resulting list called "edgelist" in network terms, users in common edge weight.

schema:

users id name  posts id title body  users_posts user_id post_id 

desired output:

postname1         postname2     users_in_common here's title    title #2      2 post      title #2      11 

i tried searching didn't know right search terms among many-to-many, join, 3 tables, count, pairs, shared, etc. help!

my query produces pairs of posts including without common users (will have 0 in users_in_common in such case). try solution on sql fiddle or see code:

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

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -