我有一张用户签入和签出时间的表(“ lms_attendance”),如下所示:id user time io (enum)1 9 1370931202 out2 9 1370931664 out3 6 1370932128 out4 12 1370932128 out5 12 1370933037 in我正在尝试创建此表的视图,该表将仅输出每个用户ID的最新记录,同时给我“ in”或“ out”值,如下所示:id user time io2 9 1370931664 out3 6 1370932128 out5 12 1370933037 in到目前为止,我已经很接近了,但是我意识到视图将不接受子查询,这使它变得更加困难。我得到的最接近的查询是:select `lms_attendance`.`id` AS `id`, `lms_attendance`.`user` AS `user`, max(`lms_attendance`.`time`) AS `time`, `lms_attendance`.`io` AS `io` from `lms_attendance` group by `lms_attendance`.`user`, `lms_attendance`.`io`但是我得到的是:id user time io3 6 1370932128 out1 9 1370931664 out5 12 1370933037 in4 12 1370932128 out这很接近,但并不完美。我知道最后一个分组依据不应存在,但是如果没有它,它将返回最近的时间,但不会返回其相对IO值。有任何想法吗?谢谢!
3 回答
小唯快跑啊
TA贡献1863条经验 获得超2个赞
基于@TMS答案,我喜欢它,因为不需要子查询,但是我认为省略该'OR'部分就足够了,而且更容易理解和阅读。
SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
ON t1.user = t2.user
AND t1.time < t2.time
WHERE t2.user IS NULL
如果您对空时间行不感兴趣,可以在WHERE子句中过滤它们:
SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
ON t1.user = t2.user
AND t1.time < t2.time
WHERE t2.user IS NULL and t1.time IS NOT NULL
添加回答
举报
0/150
提交
取消