0

I have these columns for table comments:

id
content
add_date
uid
school_id

Rows can have the same school_id.

I want to select the latest data according to add_date, but only 1 row per school_id (no duplicate for school_id) with limit of 10.

I've tried many codes already and its not working for me. Any help would be appreciated.

0

3 Answers 3

1

This is what we call Greatest N per Group. You can achieved this by putting into a subquery so it can be joined against the non-grouped table (comments). Try this:

SELECT  c.*
FROM
        (
            SELECT school_id, MAX(add_date) maxDate
            FROM comments
            GROUP BY school_id
        ) x INNER JOIN comments c
            ON  x.school_id = c.school_ID AND
                x.maxDate = c.add_date
ORDER BY x.maxDate desc
LIMIT 10
Sign up to request clarification or add additional context in comments.

3 Comments

Probably want to add ORDER BY maxDate DESC LIMIT 10 to the subquery x. This will result in only the 10 most recent posts being pulled from comments after the aggregation. Otherwise, if there are more than 10 schools, extra lookups are done.
the OP asked for select the latest data according to add_date
Yes, and ordering desc in the subquery will find the most recent 10 by add_date. You don't need more than the 10 most recent records from x.
0
select C.ID, C.Content, t1.MaxDate as [add_date], C.uid, t1.school_id
from (selet school_id, max(add_Date) as 'MaxDate'
from comments
group by school_id) T1
inner join comments C on T1.school_id = C.school_id and C.add_Date= T1.MaxDate
LIMIT 10

If you want to choose which 10 rows return, add an order by, or a Where clause

Comments

0
select c1.*
  from comments c1
 where add_date = (select max(add_date) from comments c2 where c2.school_id =c1.school_id)
 order by add_date desc
 limit 10

create indexes on comments(add_date) and comments(school_id, add_date)

1 Comment

The other provided solutions for the problem will have to scan the entire comments table and will not scale as the table grows. This solution will read the minimum number of required rows.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.