I have 3 tables with structure as below.
tbl_activities (id, activity_type, user_id)
tbl_subscriptions (id, subscriber_id, subscribed_id)
tbl_users (id, user_name)
User can do activity such as like or comment. He can also subscribe to many users. Now I want suggest some user for him base on activity type and avoid his current subscribing users.
Let say user "A" has id=1 => I want to suggest 15 users to user "A" by most active user (user who have lots of activities) and avoid current subscribing users of user "A".
I used this query, but it takes around 15seconds to finish.
SELECT id, user_name FROM tbl_users
WHERE id IN (
SELECT t.user_id FROM (
SELECT act.user_id
FROM tbl_activities act
INNER JOIN tbl_users u
ON act.user_id=u.id
WHERE u.id NOT IN (
SELECT s.subscribed_uid
FROM tbl_subscriptions s
INNER JOIN tbl_users u1
ON s.subscribed_uid=u1.id
WHERE s.subscriber_id=1
)
GROUP BY act.user_id
ORDER BY COUNT(act.user_id)
DESC LIMIT 0,15
) AS t
)
I know it is very slow because of query "in and not in". But I could not find the best solution.
Appreciate your share about better query to solve this problem.