按字符串日期mysql搜索

时间:2017-12-07 07:48:09

标签: mysql

我需要运行按日期范围返回行的查询。 日期以字符串格式保存,如“22/11/2017” 我尝试在str_to_date中使用,但它不能很好地工作。 我的疑问:

SELECT Activities.Date AS 'dates'  FROM Attendance
                           INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                           INNER JOIN Groups ON Activities.GroupID=Groups.ID
                           INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                           WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND  (str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017" AND str_to_date(Activities.Date,'%d/%m/%Y')<='30/11/2017') GROUP BY Activities.Date
                            ORDER BY Groups.Name

结果:

'24/09/2017','24/10/2017','24/11/2017','24/12/2017','25/09/2017','25/10/2017,..

2 个答案:

答案 0 :(得分:1)

 Select STR_TO_DATE(string_date_col, '%d/%m/%y') FROM table_name...

在你的情况下,你将它转换为日期,但你再次将它与字符串进行比较,你需要将所有字符串转换为日期格式,以便它可以有一个有效的比较,所以它应该是

(str_to_date(Activities.Date,'%d/%m/%Y')>=str_to_date("01/11/2017",'%d/%m/%Y')

而不是

(str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017"

答案 1 :(得分:0)

您可以使用Activities.Date LIKE "%11/2017"之类的SQL通配卡来获取2017年11月份记录的所有活动。您的查询应该是:

SELECT Activities.Date AS 'dates'  FROM Attendance
                       INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                       INNER JOIN Groups ON Activities.GroupID=Groups.ID
                       INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                       WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND Activities.Date LIKE "%11/2017" GROUP BY Activities.Date
                        ORDER BY Groups.Name