选择某个日期,直到现在mysql

时间:2013-09-16 05:58:44

标签: mysql sql

我需要查询选择unix时间戳,范围从特定的过去日期到现在?例如,我需要选择'2013-01-01'直到当前日期。我能够在特定的一年里做到这一点。任何帮助将不胜感激。

SELECT mdl_user_info_data.data, mdl_user.firstname, mdl_user.lastname, mdl_user.id   AS  userid, SUM( mdl_quiz.fcpd ) AS cpdtotal
FROM mdl_grade_grades
INNER JOIN mdl_user ON mdl_grade_grades.userid = mdl_user.id
INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.id
INNER JOIN mdl_quiz ON mdl_grade_items.itemname = mdl_quiz.name
INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id
INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid
WHERE mdl_user_info_data.fieldid =1
AND mdl_grade_items.itemname IS NOT NULL
AND YEAR( FROM_UNIXTIME( mdl_grade_grades.timemodified ) ) =2013
GROUP BY mdl_user.id

5 个答案:

答案 0 :(得分:1)

要检查过去给定日期时间与当前日期时间之间的时间戳值,请执行以下操作:

AND mdl_grade_grades.timemodified >= '2013-07-25 15:30'
AND mdl_grade_grades.timemodified <  NOW()

答案 1 :(得分:0)

尝试以下查询

SELECT mdl_user_info_data.data, mdl_user.firstname, mdl_user.lastname, mdl_user.id   AS  userid, SUM( mdl_quiz.fcpd ) AS cpdtotal
FROM mdl_grade_grades
INNER JOIN mdl_user ON mdl_grade_grades.userid = mdl_user.id
INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.id
INNER JOIN mdl_quiz ON mdl_grade_items.itemname = mdl_quiz.name
INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id
INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid
WHERE mdl_user_info_data.fieldid =1
AND mdl_grade_items.itemname IS NOT NULL
AND mdl_grade_grades.timemodified <  date('d-m-Y')
GROUP BY mdl_user.id

答案 2 :(得分:0)

AND DATE(FROM_UNIXTIME(mdl_grade_grades.timemodified)) between '2013-01-01' and  
DATE(NOW()); 

答案 3 :(得分:0)

您可以创建一个存储过程并将日期作为参数传递给它。 在这里,我通过添加结束日期使其更加灵活。

CREATE PROCEDURE `NewProc`(IN StartDate date,IN EndDate date)
BEGIN

SELECT mdl_user_info_data.data, mdl_user.firstname, mdl_user.lastname, mdl_user.id   AS  userid, SUM( mdl_quiz.fcpd ) AS cpdtotal
FROM mdl_grade_grades
INNER JOIN mdl_user ON mdl_grade_grades.userid = mdl_user.id
INNER JOIN mdl_grade_items ON mdl_grade_grades.itemid = mdl_grade_items.id
INNER JOIN mdl_quiz ON mdl_grade_items.itemname = mdl_quiz.name
INNER JOIN mdl_course ON mdl_grade_items.courseid = mdl_course.id
INNER JOIN mdl_user_info_data ON mdl_user.id = mdl_user_info_data.userid
WHERE mdl_user_info_data.fieldid =1
AND mdl_grade_items.itemname IS NOT NULL
AND mdl_grade_grades.timemodified between StartDate and EndDate 
GROUP BY mdl_user.id

END;

答案 4 :(得分:0)

只需更换此行:

AND YEAR(FROM_UNIXTIME(mdl_grade_grades.timemodified)) = 2013

为:

AND FROM_UNIXTIME(mdl_grade_grades.timemodified)
   BETWEEN '2012-01-01 12:00'
   AND now()

您似乎将unix时间戳存储在timemodified列中。您应该考虑将其更改为timestamp类型 - 这将允许利用该字段的索引。现在,您的查询(以及此查询)也很慢,因为它必须在该表的每一行上计算FROM_UNIXTIME(),然后才比较年份或日期。

<强>更新

如果您不想更改类型,使用此方法可以使您的查询工作更快(假设timemodified列上有索引):

AND mdl_grade_grades.timemodified
   BETWEEN unix_timestamp('2012-01-01 12:00')
   AND unix_timestamp(now())