2011-10-20 34 views
2

所以我有一張5列的表格:id, user_id, news_id, comment and date。每當用戶在新聞評論區發佈內容時,數據就會插入到此表中。SQL - 按行數排序?

現在我正在嘗試製作一個頂級海報功能,它將顯示發佈最多評論的人員。

我想知道如何根據該表中存在user_id的次數來從該表中排序結果。

例如:

1 - 134(user_id) -> 20 posts(that's how many times this user_id was found in the table.) 
2 - 123 -> 19 
3 - 168 -> 15 

等。

在此先感謝。

回答

2

TSQL

select userID, count(*) 
    from userIDtable 
    group by userID 
    order by count(*) desc, userID asc 
5
SELECT user_id, COUNT (*) as comments 
FROM table 
GROUP BY user_id 
ORDER BY comments DESC 
1

我認爲你是列混淆行,但沒關係。這是很容易做到:

SELECT 
    user_id, 
    COUNT(*) posts 
FROM 
    comments 
GROUP BY 
    user_id 
ORDER BY 
    posts DESC 
0
SELECT count(user_id) C, user_id FROM RECORDS ORDER BY C LIMIT 5 
0

「所以我有5行的表:ID,USER_ID,news_id,註釋和日期每當用戶發佈了一些對新聞的評論區中的數據是插入到這張表中。「 在這個答案中,我假設你的意思是上面的5列。

select user_id, count(*) num from tableName group by user_id order by num desc;