Created
          December 23, 2014 16:52 
        
      - 
      
- 
        Save furkantektas/45be89e5d9d1c8e82a30 to your computer and use it in GitHub Desktop. 
    Get relevant items for many to many relation
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # 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