How to count similar interests in MySQL

I have 2 tables, "interests" and "users_interests".

'users_interests' just has fields useridand interestid. 'interests have only ida name.

I just need to find a user ID that has more than 3 percent. I was told that Self Join was involved, but I can not get it to work.

Someone said something like this might work:

SELECT 
      others.userid 
  FROM interests AS user 
  JOIN interests AS others 
      USING(interestid) 
  WHERE user.userid = 2 
  GROUP BY 
      others.userid 
  ORDER BY COUNT(*) DESC

But I’m out of luck.

+5
source share
2 answers
SELECT ui.userid, COUNT(*) AS common_interests
FROM users_interests ui
WHERE ui.interestid IN (
    SELECT ui2.interestid FROM users_interests ui2 WHERE ui2.userid = 2
) 
AND ui.userid <> 2
GROUP BY ui.userid
HAVING common_interests > 3;

Pay attention to the origin useridon which we base our search on ( 2) on two places in the code

+5

, " 4", ?

SELECT first1.userid, second1.userid
FROM users_interests first1, users_interests second1,
     users_interests first2, users_interests second2,
     users_interests first3, users_interests second3,
     users_interests first4, users_interests second4
WHERE
    first2.userid=first1.userid AND first3.userid=first1.userid AND first4.userid=first1.userid AND
    second2.userid=second1.userid AND second3.userid=second1.userid AND second4.userid=second1.userid AND
    first1.userid<>second1.userid AND
    first1.interestid=second1.interestid AND
    first2.interestid=second2.interestid AND first2.interestid<>first1.interestid AND
    first3.interestid=second3.interestid AND first3.interestid<>first2.interestid AND first3.interestid<>first1.interestid AND
    first4.interestid=second4.interestid AND first4.interestid<>first3.interestid AND first4.interestid<>first2.interestid AND first4.interestid<>first1.interestid

, , , , .

, , , . , , , interests SELECT.

+2

All Articles