简体   繁体   中英

SQL query to fetch the last users who created content orderd by date

I have a oneToMany relationship between User entity and Post entity. Each user can create as muck posts as he want. Tables look like:

User(id, name)

Post(id, post_owner_id, content, date) // post_owner_id is the foreign key

My goal is to fetch the last users who created posts. I started by:

SELECT * 
FROM  `post` 
ORDER BY post_date DESC 
LIMIT 0 , 30

and it is giving me correct result. But when I add GROUP BY post_user_id , it shrinks the result to only one row per user but with unordered date. What am I missing?

I believe that I need a JOIN to get the final goal but I need first to find a solution for this first part. Your help is much appreciated.

I need a table of users with the date of their last post.

SELECT post_owner_id, max(date) as maxdt
FROM  `post`
group by post_owner_id
order by maxdt desc
limit 0,30

select id, maxdt, name
from (
SELECT post_owner_id, max(date) as maxdt
FROM  `post`
group by post_owner_id) t join `User` u on u.id = t.post_owner_id

You don't even need a sub query.

SELECT u.id, u.name, max(p.`date`) as maxdt
FROM  `post` p
JOIN `User` u on u on u.id = p.post_owner_id
group by u.id, u.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM