2009-12-31 59 views
4

我有一個表叫trends_points,這個表有以下欄目:MySQL「ORDER BY」特定列中具有相同值的行數?

  • ID(行的唯一ID)
  • 用戶ID(在表已經進入該用戶的ID)
  • 長期(字)
  • 時間(Unix時間戳)

現在,我試圖運行此表的查詢將得到各行的具體時間框架如何通過有序的馬紐約時報列term出現在表中的特定時間範圍內......因此,例如,如果表具有以下行:

id | userId | term  | time 
------------------------------------ 
1 28  new year  1262231638 
2 37  new year  1262231658 
3 1  christmas  1262231666 
4 34  new year  1262231665 
5 12  christmas  1262231667 
6 52  twitter  1262231669 

我想出來的行排序是這樣的:

new year 
christmas 
twitter 

這是因爲「新的一年」在時間範圍內存在三次,「聖誕節」存在兩次,「推特」只存在一行。

到目前爲止,我已經說明它是查詢的特定時間範圍部分的簡單WHERE,GROUP BY用於停止列表中出現兩次相同的術語。

這使得下面的查詢:

SELECT * 
    FROM `trends_points` 
WHERE (time >= <time-period_start> 
    AND time <= <time-period_end>) 
GROUP BY `term` 

有誰知道我怎麼會做查詢的最後一部分? (通過多少行包含相同的「術語」列值來排列查詢的結果..)。

回答

11

用途:

SELECT tp.term, 
     COUNT(*) 'term_count' 
    FROM TREND_POINTS tp 
    WHERE tp.time BETWEEN <time-period_start> AND <time-period_end> 
GROUP BY tp.term 
ORDER BY term_count DESC, tp.term 

this question about why to use BETWEEN vs using the >=/<= operators

請記住,可能存在關係 - 當發生這種情況時,按默認順序按字母順序排列短期值,但也可能有其他標準。

此外,如果您想額外限制返回的行數/項數,則可以將LIMIT clause添加到查詢的末尾。例如,此查詢將返回前五項:

SELECT tp.term, 
     COUNT(*) 'term_count' 
    FROM TREND_POINTS tp 
    WHERE tp.time BETWEEN <time-period_start> AND <time-period_end> 
GROUP BY tp.term 
ORDER BY term_count DESC, tp.term 
    LIMIT 5 
1

COUNT()會給你組中的行數,所以只需按順序排列。

SELECT * FROM `trends_points` 
WHERE (`time` >= <time-period_start> AND `time` <= <time-period_end>) 
ORDER BY COUNT(`term`) DESC 
GROUP BY `term` 
+0

完美,非常感謝! – Simon 2009-12-31 03:13:01

+0

太棒了!另外,請考慮OMG小馬關於BETWEEN的說明。 – 2009-12-31 03:40:19

4

快速回答:

SELECT 
    term, count(*) as thecount 
FROM 
    mytable 
WHERE 
    (...) 
GROUP BY 
    term 
ORDER BY 
    thecount DESC 
2
SELECT t.term 
FROM trend_points t 
WHERE t.time >= <time-period_start> AND t.time <= <time-period_end> 
ORDER BY COUNT(t.term) DESC 
GROUP BY t.term 
相關問題