我有一个叫做的表trends_points,这个表有以下几列:
现在,我正在尝试对此表运行查询,该查询将获取特定时间范围内的行,这些行按特定时间范围内列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
Run Code Online (Sandbox Code Playgroud)
我希望这些行的排序如下:
new year
christmas
twitter
Run Code Online (Sandbox Code Playgroud)
这是因为"新年"在时间框架中存在三次,"圣诞节"存在两次,"推特"仅存在一行.
到目前为止,我已经认为它是查询的特定时间范围部分的简单WHERE和GROUP BY,以阻止相同的术语在列表中出现两次.
这使得以下查询:
SELECT *
FROM `trends_points`
WHERE ( time >= <time-period_start>
AND time <= <time-period_end> )
GROUP BY `term`
Run Code Online (Sandbox Code Playgroud)
有谁知道我如何做查询的最后部分?(按查询的结果排序多少行包含相同的"term"列值..).
OMG*_*ies 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
Run Code Online (Sandbox Code Playgroud)
请参阅此问题,了解为何使用BETWEEN与使用> =/<=运算符.
请记住,可能存在关联 - 默认情况下,按此处按字母顺序按字母顺序缩短,但可能还有其他标准.
此外,如果要另外限制返回的行/术语数,可以将该LIMIT子句添加到查询的末尾.例如,此查询将返回前五个术语:
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
Run Code Online (Sandbox Code Playgroud)