简体   繁体   English

MySQL日期范围查询

[英]MySql Query For Date Range in PHP

I have a MySql database that uses a timestamp field to track when the entry was inserted. 我有一个MySql数据库,该数据库使用时间戳字段来跟踪条目的插入时间。

Now I want to query the table for entries by a date range. 现在,我想按日期范围查询表中的条目。

I would prefer to use MySql to extract the records instead of extracting all records then iterating and comparing dates in php. 我宁愿使用MySql提取记录,而不是提取所有记录,然后在php中迭代和比较日期。

So I have a start-date and an end-date. 所以我有一个开始日期和一个结束日期。 I have tried YYYYMMDD and YYYY-MM-DD format with no success on these two kinds of queries: 我尝试了YYYYMMDD和YYYY-MM-DD格式,但在以下两种查询上均未成功:

// this doesn't appear to be working
SELECT COUNT(*) FROM table_name 
WHERE DATE(timestamp_row) BETWEEN '{$date1}' AND '{$date2};

// this doesn't appear to be working either
SELECT COUNT(*) FROM table_name 
WHERE DATE(timestamp_row) >= {$date1}
AND DATE(timestamp_row) <= {$date2};

It appears that the Mysql DATE() function turns the timestamp into this format: YYYY-MM-DD 看来Mysql DATE()函数将时间戳转换为以下格式:YYYY-MM-DD

Is there a way to do this. 有没有办法做到这一点。

You are doing the B'Day dates of users and thus hope this would be do the trick of formatting and selection of date 您正在执行用户的B'Day日期,因此希望这可以解决格式和选择日期的问题

select id from my_table
 where
 timestamp < date_format(date_add(CURRENT_TIMESTAMP(), interval 1 day),
             '%Y%m%d000000' ) AND timestamp >=  date_format(CURRENT_TIMESTAMP(),
             '%Y%m%d000000')

Isearch the data by id but the date is wrong...This show 1970/01/01 我通过id搜索数据,但日期错误...此显示1970/01/01

                             $book_year= Date("Y", strtotime($year));
            $book_month= Date("m", strtotime($month));
            $book_day=Date("d", strtotime($day));
            $book_date=$year."/". $month."/". $day;
                    $book_date= Date("Y-m-d", strtotime($book_date));

Which field types of these are you using? 您正在使用哪些字段类型? 1. DATETIME, 2. DATE, 3. TIMESTAMP 1. DATETIME,2. DATE,3. TIMESTAMP

Since SELECT COUNT(*) FROM table_name WHERE DATE(timestamp_row) BETWEEN '{$date1}' AND '{$date2}; 由于从表名SELECT COUNT(*)在WHERE DATE(timestamp_row)在'{$ date1}'和'{$ date2}之间; looks ok, if you use specific values instead of '{$date1}' AND '{$date2}; 如果您使用特定值而不是'{$ date1}'和'{$ date2},则看起来还可以; maybe there is something wrong with the way time is formatted in your rows? 也许时间在行中格式化的方式有问题吗?

You can automatically convert an invalid date to the valid equivalent like this: 您可以像这样自动将无效日期转换为等效日期:

SELECT '2008-02-31' + INTERVAL 0 DAY; 选择'2008-02-31'+间隔0天;

2008-03-02 2008-03-02

You can try this 你可以试试这个

SELECT COUNT(*) FROM table_name WHERE timestamp_row BETWEEN '2011-01-01 00:00:00' AND '2011-01-31 23:59:59';

There's no need to use MySQL's DATE function in your original query. 您无需在原始查询中使用MySQL的DATE函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM