php 选择两个日期之间的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9232122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select data between two dates?
提问by Joey Morani
I'm using a database to store logs, with a column "date" which holds the date it was inserted. The format of the date is "MM/DD/YY". Please can anyone suggest how I would SELECT data in between two certain dates. For example, I tried this:
我正在使用数据库来存储日志,其中有一列“日期”,其中包含插入的日期。日期的格式为“MM/DD/YY”。请有人建议我如何在两个特定日期之间选择数据。例如,我试过这个:
$from_date = "01/01/12";
$to_date = "02/11/12";
$result = mysql_query("SELECT * FROM logs WHERE date >= " . $from_date . " AND date <= " . $to_date . " ORDER by id DESC");
while($row = mysql_fetch_array($result)) {
// display results here
}
But I guess this doesn't work because the dates aren't numbers. Thanks for the help! :)
但我想这不起作用,因为日期不是数字。谢谢您的帮助!:)
回答by Sarfraz
Use the BETWEEN
keyword:
使用BETWEEN
关键字:
"SELECT * FROM logs WHERE date BETWEEN '" . $from_date . "' AND '" . $to_date . "'
ORDER by id DESC"
回答by Brian
You can cast the fields as dates and then select between from_date and to_date
您可以将字段转换为日期,然后在 from_date 和 to_date 之间进行选择
SELECT * FROM logs WHERE date STR_TO_DATE(date, '%m/%d/%Y') between STR_TO_DATE(from_date, '%m/%d/%Y') and STR_TO_DATE(to_date, '%m/%d/%Y')
回答by Mike Dinescu
The answer to your question depends on the data type that is used to store the date
field in the logs
table.
您的问题的答案取决于用于date
在logs
表中存储字段的数据类型。
SQL (MySQL in your case) is fully capable of comparing dates. Usually, the BETWEEN .. AND ..
operator is used but that will not work correctly if the type of date
is CHAR (or VARCHAR) - in which case you will need to cast the date
field to a DATETIME before comparing.
SQL(在您的情况下为 MySQL)完全能够比较日期。通常,BETWEEN .. AND ..
会使用运算符,但如果类型date
为 CHAR(或 VARCHAR),则该运算符将无法正常工作- 在这种情况下,您需要date
在比较之前将该字段转换为 DATETIME。
回答by Stelian Matei
You need to add single quotes to the date values '01/01/12':
您需要为日期值“01/01/12”添加单引号:
$from_date = "01/01/12";
$to_date = "02/11/12";
$result = mysql_query("SELECT * FROM logs WHERE date >= '" . $from_date . "' AND date <= '" . $to_date . "' ORDER by id DESC");
回答by Mustafa
Change date parameters into Unix timestamps and then compare them. Here is the code:
将日期参数更改为 Unix 时间戳,然后进行比较。这是代码:
$from_date = "2019/01/12";
$to_date = "2019/01/15";
$from_date_unix = strtotime($from_date);
$to_date_unix = strtotime($to_date);
$result = mysql_query("SELECT * FROM logs WHERE date >= " . $from_date_unix . " AND date <= " . $to_date_unix . " ORDER by id DESC");
while($row = mysql_fetch_array($result)) {
// display results here
}