简体   繁体   English

日期之间搜索错误

[英]Wrong search between dates

In the database I have table users which have column 'birthday' 在数据库中我有表'用户'列'生日'

Here is the sql query that I use to fetch the results 这是我用来获取结果的sql查询

SELECT *
FROM (`users`)
WHERE `birthday` between '12/11/1982' and '31/01/1983'

The problems is that I get records only for year 1982 ? 问题是我只获得1982年的记录

Notice that records for 1983 year exists. 请注意,存在1983年的记录。

What could be the problem here ? 这可能是什么问题?

This is just an alternative answer from Mark Byers. 这只是Mark Byers的另一个答案。 If the data type of your column birthday is varchar and has format of dd/MM/yyyy , please do read this; 如果您的列birthday的数据类型是varchar并且格式为dd/MM/yyyy ,请阅读此内容; otherwise, read from Mark Byer's . 否则,请阅读Mark Byer的

The first thing you need to do is to convert your column into DATE or DATETIME datatype by using STR_TO_DATE , 您需要做的第一件事是使用STR_TO_DATE将列转换为DATEDATETIME数据类型,

SELECT *
FROM  `users`
WHERE STR_TO_DATE(`birthday`,'%d/%m/%Y')
          between '1982-01-12' and '1983-12-31'

SOURCES 来源

You should put the year first in your date literals: 您应该将年份放在日期文字中:

SELECT *
FROM `users`
WHERE `birthday` between '1982-11-12' AND '1983-01-31'

From the documentation : 文档

Date and time values can be represented in several formats, such as quoted strings or as numbers, depending on the exact type of the value and other factors. 日期和时间值可以用多种格式表示,例如带引号的字符串或数字,具体取决于值的确切类型和其他因素。 For example, in contexts where MySQL expects a date, it interprets any of '2015-07-21', '20150721', and 20150721 as a date. 例如,在MySQL期望日期的上下文中,它将'2015-07-21','20150721'和20150721中的任何一个解释为日期。

If you are using a varchar type then it still makes sense to put the date first (both in the data and in the query) because then your dates will sort correctly when using the default sorting order. 如果您使用varchar类型,那么将日期放在第一位(数据和查询中)仍然是有意义的,因为在使用默认排序顺序时,您的日期将正确排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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