MySQL compare DATE string with string from DATETIME field

前端 未结 7 670
闹比i
闹比i 2020-11-29 19:55

I have a question: Is it possible to select from a MySQL database by comparing one DATE string \"2010-04-29\" against strings that are stored as DATETIME (2010-04-29 10:00)?

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 20:52

    If you want to select all rows where the DATE part of a DATETIME column matches a certain literal, you cannot do it like so:

    WHERE startTime = '2010-04-29'
    

    because MySQL cannot compare a DATE and a DATETIME directly. What MySQL does, it extends the given DATE literal with the time '00:00:00'. So your condition becomes

    WHERE startTime = '2010-04-29 00:00:00'
    

    Certainly not what you want!

    The condition is a range and hence it should be given as range. There are several possibilities:

    WHERE startTime BETWEEN '2010-04-29 00:00:00' AND '2010-04-29 23:59:59'
    WHERE startTime >= '2010-04-29' AND startTime < ('2010-04-29' + INTERVAL 1 DAY)
    

    There is a tiny possibility for the first to be wrong - when your DATETIME column uses subsecond resolution and there is an appointment at 23:59:59 + epsilon. In general I suggest to use the second variant.

    Both variants can use an index on startTime which will become important when the table grows.

提交回复
热议问题