简体   繁体   中英

MySQL How to SELECT data from table which recorded today?

Use PHP and MySQL. In my table, there is date field (datetime) recorded by NOW() sql function. Example value of data in this field is 2010-10-07 10:57:36 . How can I SELECT all data which day-month-year is today. I try to use code as below:

  SELECT * FROM table WHERE date=????

Try this:

SELECT * FROM table WHERE date > CURDATE();

CURDATE() will return the current date as 2011-10-07 which will be cast to 2011-10-07 00:00:00 when comparing datetime s to it.

Note that if you use DATE(date) = CURDATE() you will run a date conversion for every row in the table, which will be really bad for your perfomance if you have many rows and/or you need to run the query often. Also make sure you have an index on date , otherwise both methods will be even slower.

SELECT * FROM table where DATE(date)=CURDATE()

SELECT * FROM tableName WHERE DATE(fieldDate) = DATE(NOW());

The date_format function allows you to easily switch between various granularities:

Select everything from the same day:

select * from table 
where date_format(date, '%Y-%m-%d') = date_format(now(), '%Y-%m-%d');

From the same month:

select * from table 
where date_format(date, '%Y-%m') = date_format(now(), '%Y-%m');

From the same year:

select * from table 
where date_format(date, '%Y') = date_format(now(), '%Y');

From the same hour:

select * from table 
where date_format(date, '%Y-%m-%d %H') = date_format(now(), '%Y-%m-%d %H');

and so on.

Try this

SELECT * FROM table WHERE DATE(my_date)=DATE(now())

my_date -> column name
SET @day = '2017-12-12' ;

SELECT * FROM table WHERE dateColumn BETWEEN DATE(@day) AND DATE_ADD(DATE(@day), INTERVAL 1 DAY ) ;

使用这样的东西它完全适用于我的代码(访问数据库):

select * from Table t where t.column>=Date() and t.column< Date() + 1

之间使用。

select * from table date between '2010-10-06' and '2010-10-08';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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