Question

I am looking to load all posts, sorted by newest first, but also limit them to three per user. I have no idea how to do that though! Here's the SQL I have currently to create the table and select the posts.

SELECT p.title, u.firstname, u.lastname
  FROM post p  
  JOIN user u
    ON p.user_id=u.id
 ORDER
    BY u.id, p.ctime DESC
#LIMIT TO 3 by user
;
Was it helpful?

Solution

This is what you can do

select
u.*,
p.*
from
user u
left join
(
   select  
   p1.*
   FROM    
   post p1
   where    
    (
       select   
       count(*) 
       from
       post p2
       WHERE 
       p1.user_id = p2.user_id
       AND p1.id <= p2.id
    ) <= 3
   order by p1.id desc
) p ON  u.id = p.user_id
order by u.id 

Took help from MySQL Limit LEFT JOIN Subquery after joining

OTHER TIPS

Something like this might work

SELECT u.*,up.* FROM user u LEFT JOIN

(

SELECT `p`.`title`, `u`.`firstname`, `u`.`lastname`
  FROM `post` `p`  
 ORDER
    BY `p`.`ctime` DESC
LIMIT 3 

) 

up on up.user_id = u.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top