用户加载三个帖子

时间:2014-05-06 17:34:07

标签: mysql select

我希望加载所有帖子,按最新排序,但也限制为每个用户3个。我不知道怎么做!这是我当前创建表并选择帖子的SQL。

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
;

2 个答案:

答案 0 :(得分:1)

这是你可以做的

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 

MySQL Limit LEFT JOIN Subquery after joining

获得帮助

答案 1 :(得分:0)

这样的事情可能会起作用

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