get values from table only for a specific day in mysql

我只是一个虾纸丫 提交于 2019-12-04 19:30:38
Ilmari Karonen

First of all, you should store your time values in a DATETIME (or possibly TIMESTAMP) column. Then follow the answers given to this question.

However, if you really insist on doing this with strings, you could always use a LIKE comparison:

SELECT * FROM `call` WHERE date_time LIKE '12/15/2012 %'

(demo on sqlize.com)

Of course, this only works for finding all records for a single day (or, with appropriate modification, for a single hour / minute / month / year / etc.). If you need more complicated selection criteria, I'd strongly suggest switching to a real DATETIME column.

dani herrera

Assuming you are storing dates as datetime field, you should convert data to Date type.

When you write:

$from= 12/15/2012

PHP do a division: 12 / 15 and then ( 12 / 15 ) / 2012

An approach will be declare $from as string and cast to date in query:

$from= '12/15/2012'
...
"select * from call where (date_time BETWEEN STR_TO_DATE('$from', '%m/%d/%Y') ..."

The right query for a index friendly plan is:

select * 
from   `call` 
where  date_time >= STR_TO_DATE('$from', '%m/%d/%Y') and 
       date_time < date_add( STR_TO_DATE('$to', '%m/%d/%Y'), interval 1 day)

See it in sqlfiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!