I have a MySQL database with 3 tables: users, posts, and users_posts. The users-posts relationship is many-to-many. How can I get a list of all pairs of posts and how many users they have in common? It essentially gives me a list of posts and how many users have commented on both. The point is to have data ready to import into network analysis software. The resulting list is called an “edgelist” in network terms, the users in common is an 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 a title Title #2 2
Another post Title #2 11
I tried searching but didn’t even know the right search terms among many-to-many, join, three tables, count, pairs, shared, etc. Thanks for your help!
My query produces all pairs of posts including those without common users (will have
0inusers_in_commonin such case). Try my solution on SQL Fiddle or see the code: