Skip to content

Instantly share code, notes, and snippets.

@furkantektas
Created December 23, 2014 16:52
Show Gist options
  • Save furkantektas/45be89e5d9d1c8e82a30 to your computer and use it in GitHub Desktop.
Save furkantektas/45be89e5d9d1c8e82a30 to your computer and use it in GitHub Desktop.
Get relevant items for many to many relation
# Reference : http://stackoverflow.com/a/7227944/1360267
SELECT
t1.*,
count(DISTINCT r2.relation2) as relevance
FROM pivot_table r1
INNER JOIN pivot_table r2 ON (r1.relation2 = r2.relation2
AND r1.relation1 <> r2.relation1)
INNER JOIN table1 t1 ON (r2.relation1 = t1.id)
WHERE r1.relation1 = '14' -- this is the id results should be related to.
GROUP BY t1.id
ORDER BY relevance DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment