简体   繁体   中英

Using MySql between clause with dates

I have always had a problem with this, for clarification purposes, when using mysql between clause, does it include the parameters or only the values that fall between them, for example:

where date between '2013-06-01' and '2013-06-06'

will this above statement include the values with a date of 2013-06-01 as well or only from '2013-06-02', and what happens if the statement stays as is, but then the date values have hours in them, will MySql automatically hours to this statement

Fabio is actually not right, if hours, minutes and seconds will be included this

where date >= '2013-06-01' and date <= '2013-06-06'

becomes internally

where date >= '2013-06-01 00:00:00' and date <= '2013-06-06 00:00:00'

So you actually just select 1 second of 2013-06-06, not the whole day!

Same with BETWEEN of course. To get the whole day of 2013-06-06 you'd have to write

where date >= '2013-06-01' and date <= '2013-06-06 23:59:59'

or

where date BETWEEN '2013-06-01' AND '2013-06-06 23:59:59'

Go ahead, try it yourself (or see it live in an sqlfiddle ):

create table foo (my_date date, my_timestamp timestamp, my_datetime datetime);
insert into foo values ('2013-06-06', '2013-06-06 12:23:34', '2013-06-06 13:35:48');

select * from foo
where
my_date <= '2013-06-06'; /*returns row*/

select * from foo
where
my_timestamp <= '2013-06-06'; /*does NOT return row*/

select * from foo
where
my_datetime <= '2013-06-06'; /*does NOT return row*/

select * from foo
where
my_timestamp <= '2013-06-06 23:59:59';  /*returns row*/

select * from foo
where
my_datetime <= '2013-06-06 23:59:59';  /*returns row*/

I suppose your column have DATETIME format. This will include both actual start time and end time. It is interpreted by mysql as it is

where date >= '2013-06-01' and date <= '2013-06-06'

If hours, minutes and seconds will be included it will act exactly the same way as in the example.

The documentation at http://dev.mysql.com/doc/refman/5.6/en/comparison-operators.html#operator_between states that the range is inclusive:

If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0. This is equivalent to the expression (min <= expr AND expr <= max) if all the arguments are of the same type.

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