我有一张看起来有点像这样的表:
ID
word
timestamp
现在我需要一个看起来像这样的结果:
word (unique)
total number of records for this word
total number of records for this word between date1 and date 2
total number of records for this word between date2 and date 3
即:我需要所有(唯一)单词的列表(我可以通过GROUP BY子句实现)和各个时段的计数。
虽然我知道如何通过多个查询和一些PHP实现这一点,但我想知道是否可以创建一个(因此更高性能)表。
有人可以帮助我吗?
答案 0 :(得分:0)
是的,而不是计算你的求和,因为布尔表达式返回true
或false
,这与1
或0
相同。
SELECT
word,
COUNT(*) AS 'total number of records for this word',
SUM(timestamp BETWEEN $date1 AND $date2) AS 'total number of records for this word between date1 and date 2',
SUM(timestamp BETWEEN $date2 AND $date3) AS 'total number of records for this word between date2 and date 3'
FROM your_table
GROUP BY word;