[英]Can't figure out how to query only for last 30 days result in mysql
Hello i have this code to count visitors number from distinct ip adrress for all days stored in the table. 您好,我有这段代码来统计表中存储的所有天数来自不同IP地址的访问者数量。
$con = mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("visitorsCount");
$page = $_GET['page']; //Page users visited with their ip
$queryTest = 'SELECT date, count(*),count(distinct ip) FROM `visitors` where section=\''.$page.'\' group by date order by date';
$result= mysql_query($queryTest);
$data = array();
while($ris=mysql_fetch_row($result))
{
$data[$ris[0]]=$ris[1]; // Render Visitor Count
}
print_r($data);
So, Print_r provides me this: Array ( [2015-02-03] => 1 [2015-05-03] => 14 )
. 因此,Print_r为我提供了这个: Array ( [2015-02-03] => 1 [2015-05-03] => 14 )
。
But i want to restrict the query only for last 30 days in $queryTest
variable. 但是我只想在$queryTest
变量中限制最近30天的查询。 How i can restrict the query only to show last 30 days records? 如何限制查询仅显示最近30天的记录? Please have a look at the sql fiddle for the table structure. 请查看表结构的sql小提琴。 table struture 桌子结构
在过滤器语句中使用BETWEEN
进行DATE_SUB()
-
SELECT date, count(*),count(distinct ip) FROM `visitors` where section=\''.$page.'\' AND date BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() group by date order by date
You can try this way to calculate ‛30 DAY‛ interval from ‛NOW‛ 您可以尝试通过这种方式从‛NOW‛计算‛30 DAY‛间隔
SELECT date, count(*),count(distinct ip)
FROM `visitors` where date >= DATE(NOW() -
INTERVAL 30 DAY) AND date <= NOW() group by date order by
date;
You can also use BETWEEN clause on you WHERE condition. 您还可以在WHERE条件上使用BETWEEN子句。
$dt=strtotime("-30 days")
$dt=date("Y-m-d H:i:s",$dt);
$queryTest = 'SELECT date, count(*),count(distinct ip) FROM `visitors` where section=\''.$page.'\' AND date>=\'' . $dt . '\' group by date order by date';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.