我有一个(MySQL)表,其中包含两个日期/时间字段:start
和end
(每个类型datetime
)。我需要一个查询,它为我提供某个用户和定义日期的最低值start
和最高值。end
我终于成功了以下查询:
SELECT job.id, job.user_id, job.start, last.end
FROM job
JOIN job AS last
ON job.user_id = last.user_id
AND DATE( job.start ) = DATE( last.start )
AND last.end = (SELECT max( last2.end)
FROM job AS last2
WHERE last2.user_id = last.user_id
AND DATE( last2.end ) = DATE( last.end ))
WHERE job.user_id = 1
AND DATE( job.start ) = '2012-05-28'
ORDER BY job.start ASC
LIMIT 0,1
尽管它有效,但它并不“感觉”正确。有没有更简单的方法来做到这一点?非常感谢任何帮助和提示。谢谢!
示例数据:
user_id start end
1 2012-05-28 07:13:00 2011-04-26 07:45:00
1 2012-05-28 08:15:00 2011-04-26 08:50:00
1 2012-05-28 05:32:00 2011-04-26 05:51:00
1 2012-05-28 08:50:00 2011-04-26 09:50:00
1 2012-05-28 15:10:00 2011-04-26 15:40:00
1 2012-05-27 16:11:00 2011-04-26 16:46:00
2 2012-05-28 09:50:00 2011-04-26 10:35:00