我需要一个查询,它会从datetime
中存储的日期减去1个月,以便我可以在谷歌折线图中使用它。我现在的查询是
$sql_query = "SELECT count(ip_address) AS count,
DATE(visit_date_time) as visit_date_time
FROM db_views
WHERE user_id = $id
GROUP BY DATE(visit_date_time)
ORDER BY visit_date_time LIMIT 30 ";
减去1个月就像“0月1日”,“1月2月”.....,“11月12日”。
我使用过dateadd& datesub但没有得到理想的结果并最终出错。
更新
这是完整的代码。
$sql_query = "SELECT count(ip_address) AS count, DATE(visit_date_time) as visit_date_time, MONTH(DATE(visit_date_time)) - 1 mon FROM db_views WHERE user_id = '".$_SESSION[$mainfunctions->GetLoginSessionVar()]."' GROUP BY DATE(visit_date_time) ORDER BY visit_date_time LIMIT 30 ";
$result = mysqli_query($mainfunctions->connection,$sql_query);
echo "{ \"cols\": [ {\"id\":\"\",\"label\":\"Date\",\"pattern\":\"\",\"type\":\"date\"}, {\"id\":\"\",\"label\":\"Views\",\"pattern\":\"\",\"type\":\"number\"} ], \"rows\": [ ";
$total_rows = mysqli_num_rows($result);
$row_num = 0;
while($row = mysqli_fetch_array($result)){
$row_num++;
$vDate = str_replace("-", ",",$row['visit_date_time']);
if ($row_num == $total_rows){
echo "{\"c\":[{\"v\":\"Date(".$vDate.")\",\"f\":null},{\"v\":" . $row['count'] . ",\"f\":null}]}";
} else {
echo "{\"c\":[{\"v\":\"Date(".$vDate.")\",\"f\":null},{\"v\":" . $row['count'] . ",\"f\":null}]}, ";
}
}
echo " ] }";
mysqli_close($mainfunctions->connection);
我的输出:{"v":"Date(2017,01,02)","f":null},{"v":6,"f":null}
所需输出:{"v":"Date(2017,00,02)","f":null},{"v":6,"f":null}
答案 0 :(得分:1)
您可以在查询中使用它:
SELECT DATE_FORMAT('2017-01-21 12:36:32','%m') -1;
结果:0
<强>样品强>
得到以0开头的月份数。month_number 1和2得到相同的结果
$sql_query = "SELECT count(ip_address) AS count,
DATE(visit_date_time) as visit_date_time,
MONTH(visit_date_time) as month_number_1,
DATE_FORMAT(visit_date_time,'%m') -1 as month_number_2
FROM db_views
WHERE user_id = $id
GROUP BY DATE(visit_date_time)
ORDER BY visit_date_time LIMIT 30 ";
答案 1 :(得分:1)
使用MONTH
函数从日期时间中提取月份(在您的情况下可能为visit_date_time
)并从中减去1。
SELECT
COUNT(ip_address) AS count,
DATE(visit_date_time) AS visit_date_time,
MONTH(DATE(visit_date_time)) - 1 mon
FROM
db_views
WHERE
user_id = $id
GROUP BY DATE(visit_date_time)
ORDER BY visit_date_time
LIMIT 30
答案 2 :(得分:0)
在mysql中没有找到任何正确的解决方案。所以我使用PHP代码来获得所需的输出。这是用于减去1个月的代码
$vDate = str_replace("-","",$row['visit_date_time'])-100;
$vDate = substr_replace($vDate,",",6,0);
$vDate = substr_replace($vDate,",",4,0);
如果mysql中有任何解决方案。请告诉我。