简体   繁体   中英

Limit on Group by in Mysql

In my web application, I would like to show a list of my users. Users can have different statuses (FB-like). I want to display the last 3 statuses below each user's name.

Dinosaur
   I'm a dino!
   I eat meat!
   I like cows!
Fish
   Blub!
   I don't like dinosaurs!
   Going for a swim!

I have the following SQL query:

SELECT s.status, u.voornaam, u.achternaam FROM status AS s INNER JOIN sportjefit_user AS u ON s.user = u.id where u.begeleider='53' group by id desc limit 3

However, this returns only the top 3 of the results, in this case it would only show the Dinosaur's statuses. I want to show the top 3 statuses for every users though. Can I do this with a group by and put a limit on this or do I need multiple queries here? And, if I do need multiple queries, how would I go about implementing this? The number of users will keep increasing as my application grows.

Can someone help me out?

Thanks.

I'd use multiple queries like this:

select all users
for each user
    select last 3 statuses

using

SELECT * FROM sportjefit_user

and

SELECT status FROM status WHERE userid = ? ORDER BY id DESC LIMIT 3

How many users do you anticipate? If you're trying to show all users on a page, I'd paginate them. Hope this helps.

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