I have a table "student_points".
id user_id points subject_id
1 10 45 22
2 11 75 23
3 12 78 24
4 10 13 23
5 12 65 23
and so on ...
This table contain about 1000 records of users and points. I want 10 records based on points (Max points first) So I can use mysql query as
Select * from student_points order by points limit 0,10
Now the requirement is that we need to group these 10 records based on user_id For example in first 10 records three are 3 students records so they should display in group. End result should be like
id user_id points subject_id
3 12 78 24
5 12 65 23
1 10 45 22
4 10 13 23
2 11 75 23
You can see that first record is based on most point and it student id is 12, now they are group according to user_id.
I tried two order by . I also tried to array_multisort after getting result but both are not working properly.
Please suggest any way, Either mysql query or group after getting result.
Thanks
This should work just add a limit to whatever number you want to limit by
select sp.id, sp.user_id, sp.points
from student_points sp
join (select user_id, max(points) as sort_by from student_points group by user_id) sort_table on sp.user_id = sort_table.user_id
order by sort_table.sort_by desc, sp.user_id, sp.points desc;
To get your required result I have written the query :
SELECT * FROM (
Select * from student_points order by points limit 0,10
) As st
GROUP BY user_id,subject_id
ORDER BY points DESC
Please try this. Let me know if this is not work for you.
I guess you need to wrap up your query in a subquery and later sort the results based on user_id
and points
.
SELECT * FROM
(
Select * from student_points order by points limit 0,10
) AS t
ORDER BY
t.user_id DESC,
t.points DESC
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.