如何从数据库中选择日,周,月,年的信息?

时间:2011-11-30 18:51:39

标签: php mysql date time

我目前通过将“投票”表中的投票值与“故事”表中的文章相加来获得“评价最高的文章”。

当前的PHP查询:

$sql = mysql_query("SELECT stories.*, SUM(votes.vote_value) as 'total_votes' FROM stories JOIN votes ON stories.id = votes.item_name GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10") or die (mysql_error("There was an error in connection"));

数据库结构:

故事表:

img1

投票表:

img2


但我想知道如何在不同的时间段内显示信息。说最高评价的文章“今天”“上周”“上个月”“去年”。基于“故事”表中的文章创建日期 st_date 。我只需要那些负责在不同时间段内获取数据的4个(今天,上周,月,年)不同的查询或部分。

3 个答案:

答案 0 :(得分:1)

SELECT stories.*, SUM(votes.vote_value) as 'total_votes' 
FROM stories 
JOIN votes 
   ON stories.id = votes.item_name 
WHERE (
       (st_date BETWEEN (NOW(), DATE_SUB(NOW(), INTERVAL 7 DAY))
       OR
       (st_date BETWEEN (DATE_SUB(NOW(), INTERVAL 14 DAY, DATE_SUB(NOW(), INTERVAL 7 DAY))
      )
GROUP BY stories.id 
ORDER BY total_votes DESC LIMIT 10") 

答案 1 :(得分:1)

$date1 = "TO_DAYS(NOW()) - TO_DAYS(stories.st_date) = 0";
$date2 = "TO_DAYS(NOW()) - TO_DAYS(stories.st_date) <= 7";
$date3 = "TO_DAYS(NOW()) - TO_DAYS(stories.st_date) <= 31";
$date4 = "TO_DAYS(NOW()) - TO_DAYS(stories.st_date) <= 365";

$query = "SELECT stories.*, SUM(votes.vote_value) as 'total_votes' FROM stories JOIN votes ON stories.id = votes.item_name WHERE ".$date1." GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10"
$query = "SELECT stories.*, SUM(votes.vote_value) as 'total_votes' FROM stories JOIN votes ON stories.id = votes.item_name WHERE ".$date2." GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10"
$query = "SELECT stories.*, SUM(votes.vote_value) as 'total_votes' FROM stories JOIN votes ON stories.id = votes.item_name WHERE ".$date3." GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10"
$query = "SELECT stories.*, SUM(votes.vote_value) as 'total_votes' FROM stories JOIN votes ON stories.id = votes.item_name WHERE ".$date4." GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10"

答案 2 :(得分:1)

快速修正上述部分答案。我相信OP正在寻找AVG()而不是SUM(),因为可能有1000票,1票,100票5,所以要获得最高评价,你需要AVG。要获得“最常评分”,你可以做COUNT()。 SUM()本身实际上并没有告诉你多少。 200x5 = 1000x1 = 300x3 + 100X1

如果将st_date更改为timestamp,除了其他解决方案中提到的其他日期函数外,还可以使用timestampdiff。将DAY更改为MONTH或YEAR,将&lt; 7更改为&lt; 1,将其更改为月/年,或者将其保留为天数并执行30/365

$query = "SELECT stories.*, AVG(votes.vote_value) as 'total_votes' 
FROM stories JOIN votes ON stories.id = votes.item_name 
WHERE abs(timestampdiff(DAY, stories.st_date, NOW())) < 7 
GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10"

此外,上述查询可为您提供在所需期间内创建的评分最高的文章。如果您决定在创建时间段内查看评分最高的文章,请更改您的where子句以匹配投票日期

$query = "SELECT stories.*, AVG(votes.vote_value) as 'total_votes' 
FROM stories JOIN votes ON stories.id = votes.item_name 
WHERE abs(timestampdiff(DAY, votes.date, NOW())) < 7 
GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10"

您也可以在一个查询中同时合并文章创建和投票期。

最后但并非最不重要的一点是,您应该将“日期”列的名称更改为其他内容,例如vote_date。日期是保留字,将其用于列名称

并不是一个好主意