Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Robin is correct on the date field. If you are using a function, it will have to compute that for however many entries its scanning against. The way I have it below uses MySQL variables. I calculate it ONCE into an @StartDate and use THAT value for the join clause.</p> <p>The only additional thing I changed was adding the "STRAIGHT_JOIN" clause. On many instances, I've found that it has helped myself and others to optimize the query. It prevents MySQL from trying to interpret the query in another way by possibly looking at the Activity table first since its a smaller file and then back-linking from that one. "STRAIGHT_JOIN" tells the optimizer to do it in the order you've listed.</p> <pre><code>SELECT STRAIGHT_JOIN a.activity_id, b.activity_name, count(a.activity_id) as total_count FROM ( select @StartDate := date_Sub( now(), interval 30 day ) sqlvars, friends as f INNER JOIN activities as a on a.user_id = f.friend_id and a.created_at &gt;= @StartDate INNER JOIN activity as b on a.activity_id = b.activity_id WHERE f.user_id = 1 and f.is_approved = 1 GROUP by a.activity_id ORDER by total_count DESC LIMIT 5 </code></pre> <p><strong>Per feedback</strong></p> <p>That being the case, and having this "rolling 30 days ago" cycle, I would then resort to a nightly table creation that is nothing but a creation by user ID, activity and count and query from that instead...</p> <pre><code>create table DailyRollupActivity select a.user_id, a.activity_id, count(*) total_count from ( select @StartDate := date_Sub( now(), interval 30 day ) sqlvars, Activities a where a.created_at &gt;= @StartDate group by a.User_ID, a.Activity_ID </code></pre> <p>Ensure you have an index on this daily aggregate table by the ( user ID and total count ) then query directly to this based on the friend ID ordered by total_count descending and limit 5. Small price to pay to have a nightly trigger / event / script to be run to create this ONCE. How critical is it to see activity for the current date too. Is the activity that drastic that one day activity would skew what you otherwise want to present to the user?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload