0

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.

1
  • If you like, consider following this simple two-step course of action: 1. If you have not already done so (you haven't), provide proper DDLs (and/or an sqlfiddle) so that we can more easily replicate the problem. 2. If you have not already done so (again, you haven't), provide a desired result set that corresponds with the information provided in step 1.
    – Strawberry
    May 27, 2015 at 10:40

1 Answer 1

0

I just solved my problem by adding index to related fields in those 3 tables. It speeds up around 300 times from 15s to 50ms.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.