前言:我试图找到答案,虽然在一些已回答的问题中有一些相似之处,但没有匹配。
我正在尝试生成3个月的报告,但只有当前日期返回一个值。
<?php
// Db connect
include_once ('db.php');
global $con2;
// 3 month reports
$date_from = date("d-m-Y", strtotime(" -3 months"));
$date_to = date('d-m-Y');
// Count
$get = "select * from table1 where date between '$date_from' and '$date_to'";
$get_connect = mysqli_query($con2, $get);
$get_rows = mysqli_num_rows($get_connect);
// Display data
echo $get_rows;
?>
其他信息。 已存储在table1的date列中的日期与变量的格式完全相同,例如:10-10-2017 从今天起的礼物正在展示,但没有别的。这是因为PHP只能读到第一个 - 破折号?
答案 0 :(得分:2)
使用dd-mm-yyyy字符串作为日期将无法正常使用&#34;在&#34;
之间select
*
from (
select '10-10-2017' as 'date' union all
select '11-11-2017' as 'date' union all
select '10-10-1989' as 'date' union all
select '10-10-2020' as 'date' union all
select '10-10-3017' as 'date'
) table1
where `date` between '10-10-2017' and '11-11-2017'
order by `date`
date
1 10-10-2017
2 10-10-2020
3 10-10-3017
4 11-11-2017
但转换为实际日期会:
select
* , str_to_date(`date`,'%d-%m-%Y')
from (
select '10-10-2017' as 'date' union all
select '11-11-2017' as 'date' union all
select '10-10-1989' as 'date' union all
select '10-10-2020' as 'date' union all
select '10-10-3017' as 'date'
) table1
where str_to_date(`date`,'%d-%m-%Y') between str_to_date('10-10-2017','%d-%m-%Y') and str_to_date('11-11-2017','%d-%m-%Y')
order by str_to_date(`date`,'%d-%m-%Y')
date str_to_date(`date`,'%d-%m-%Y')
1 10-10-2017 10.10.2017 00:00:00
2 11-11-2017 11.11.2017 00:00:00
另外:&#34;之间的关系&#34;在SQL中实现的是第一个值必须低于第二个值(即值的重要序列)。那是因为&#34;在&#34;之间实际上只是somevalue >= compare_val_low and somevalue <= compare_val_high
的语法快捷方式,如果反转比较值,它将返回NULL,除非somevalue
恰好等于一个或两个比较值。使用字符串可以很容易地看到更低的日期,实际上是更高的价值&#34;由于字符串排序的性质,例如这可能&#34;看&#34;确定:
between '29-08-2017' and '11-11-2017'
但它根本不行,因为&#39; 29&#39;高于&#39; 11&#39;并且之间不会返回任何行。