Question

I have a db with tables like users, interests and tags.

users table is something like this:

user_id  |  name  |  city
   15       John     New York
   18       Helen    Virgina

interests table is something like this:

interest_id  |  user_id  |  tag_id
    1              15         23
    2              15         24
    3              15         25
    4              18         23
    5              18         27

tags table is something like this:

tag_id  |  description
   23        Skiing
   24        TV
   25        Movies
   26        Music
   27        Seinfeld

Tables say that John and Helen are both interested in Skiing.

I want to make a sql query which will be resulted as John and Helen have 1 similar interest and echo them such as;

Helen 1 interest<br />
Jack 2 interests<br />

How can I do this?

And also, Are there any other better ways in terms of db schema?

As a newbie, I've look around and tried different implementations but not able to succeed.

Was it helpful?

Solution

To count how many interests user has in common with others:

SELECT u2.name, count(*)
FROM   interests AS i1 
       JOIN users AS u1 
         ON u1.user_id = i1.user_id 
       JOIN interests AS i2 
         ON i1.tag_id = i2.tag_id 
       JOIN users AS u2 
         ON u2.user_id = i2.user_id 
            AND u1.user_id <> u2.user_id 
       JOIN tags AS t 
         ON i1.tag_id = t.tag_id 
WHERE  u1.name = 'John'
GROUP BY u2.name; 

http://sqlfiddle.com/#!2/80aad/1

As for the schema, the junction table would make more sense if it would be named users_tags. Also the id column on interests is not needed in this schema, the combination (user_id, tag_id) is a natural candidate for a primary key and you're gonna need to put UNIQUE index on it anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top