2016-09-21 61 views
1

我有一個表「student_points」。命令和排序結果mysql或使用php數組funciton

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 

等等...

此表包含約1000個記錄的用戶和點。 我想基於分10條(最大分排名第一) 所以我可以使用MySQL查詢作爲

Select * from student_points order by points limit 0,10 

現在的要求是,我們需要組這10條記錄基於USER_ID 例如,在第一個10條三個是三個學生的記錄,所以他們應該在小組中顯示。 最終結果應該是像

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 

你可以看到,第一個記錄是基於2008年的點,並將其學生證是12,現在他們是根據USER_ID組。

我嘗試了兩個命令。 我也嘗試array_multisort後得到的結果,但都沒有正常工作。

請以任何方式提出建議,要麼是mysql查詢,要麼是得到結果後的組。

感謝

+0

是否需要每個user_id的10條記錄按點降序排列? – 1000111

+3

ORDER BY user_id DESC,points DESC? – jitendrapurohit

+0

你想總結一下這些觀點吧? –

回答

0

我想你需要用你的查詢在子查詢中,後來基於user_idpoints對結果進行排序。

SELECT * FROM 
(
    Select * from student_points order by points limit 0,10 
) AS t 
ORDER BY 
    t.user_id DESC, 
    t.points DESC 
+1

我希望聽到** downvoting ** – 1000111

+0

@ 1000111背後的原因,您好,請再次閱讀問題,我已編輯。 – Rich5757

+0

您的要求仍然可以通過此查詢來實現。請試試看,並告訴我@ Rich5757 – 1000111

1

這應該只是增加一個限制,無論數量要通過

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; 
1

限制要得到你需要的結果我已經寫查詢:

SELECT * FROM (
    Select * from student_points order by points limit 0,10 
) As st 
GROUP BY user_id,subject_id 
ORDER BY points DESC 

請試試這個。讓我知道如果這不適合你。