Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize date time search in Mysql?

this is my basic date-time structure:

primary  key(datetime)         key
auot_id  date_time             user_id
1        2010-10-01 20:32:34    1
2        2010-10-02 20:32:34    1
3        2010-11-03 20:32:34    2
4        2010-10-04 20:32:34    1
5        2010-11-05 20:32:34    1

And I want to get the result of the day(date_time) at '2010-10' and the user_id = '1'; My SQL is:

SELECT * FROM datetime WHERE user_id = 1 AND DATE_FORMAT(date,'%Y-%m') = '2010-10'

but the EXPLAIN code display:

SIMPLE datetime ALL (NULL) (NULL) (NULL) (NULL) 5 Using where

so ,this line of code doesn't seem to be very effectively。How could I to construct the table to make my search more effective??

Thank you very much!!

like image 900
qinHaiXiang Avatar asked Nov 20 '10 14:11

qinHaiXiang


People also ask

How do I select a date range in MySQL?

How to Select rows from a range of dates with MySQL query command. If you need to select rows from a MySQL database' table in a date range, you need to use a command like this: SELECT * FROM table WHERE date_column >= '2014-01-01' AND date_column <= '2015-01-01';

What is Getdate () in MySQL?

The GETDATE function is used to retrieve the current database system time in SQL Server. A common use of GETDATE is to get today's date.


2 Answers

Using a function on a column in a WHERE clause prevents efficient usage of an index on that column. Try this instead:

SELECT *
FROM `datetime`
WHERE user_id = 1
AND `date` >= '2010-10-01' AND `date` < '2010-11-01'

Add an index on (user_id, date).

like image 55
Mark Byers Avatar answered Oct 17 '22 11:10

Mark Byers


SELECT *
FROM yourTable
WHERE datatime
BETWEEN '2010-10-01' AND '2010-11-01'

efficient and accepts indexing too.

like image 41
heav3n Avatar answered Oct 17 '22 12:10

heav3n