2009-12-31 80 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 
相关问题