[英]Returning the next-to-last entry using MySQL
A little info: people check-in but they don't check out. 一些信息:人们正在办理登机手续,但他们没有退房。 Each check-in creates an auto-incremented entry into the _checkins table with a timestamp, MemberID, etc.
每次签入都会在_checkins表中创建带有时间戳,MemberID等的自动递增的条目。
Here's the data the query needs to return: 这是查询需要返回的数据:
I have it all working except the last part. 除了最后一部分,我都工作了。 I feel like LIMIT is going to be part of the solution but I just can't find a way to implement it correctly.
我觉得LIMIT将成为解决方案的一部分,但我只是找不到正确实现它的方法。 Here's what I've got so far:
到目前为止,这是我得到的:
SELECT m.ImageURI, m.ID, m.FirstName, m.LastName,
ROUND(time_to_sec(timediff(NOW(), MAX(ci.Created))) / 3600, 1) as
'HoursSinceCheckIn', CheckIns
FROM _checkins ci LEFT JOIN _members m ON ci.MemberID = m.ID
INNER JOIN(SELECT MemberID, COUNT(DISTINCT ID) as 'CheckIns'
FROM _checkins
WHERE(
Created BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
)
GROUP BY MemberID
) lci ON ci.MemberID=lci.MemberID
WHERE(
ci.Created BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
AND TIMESTAMPDIFF(HOUR, ci.Created, NOW()) < 2
AND ci.Reverted = 0
)
GROUP BY m.ID
ORDER BY CheckIns ASC
You can simplify greatly (and make your code safer, as well): 您可以大大简化(也可以使代码更安全):
SELECT _Members.ImageURI, _Members.ID, _Members.FirstName, _Members.LastName,
ROUND(TIME_TO_SEC(TIMEDIFF(NOW(), _FilteredCheckins.lastCheckin)) / 3600, 1) AS hoursSinceCheckIn, _FilteredCheckins.checkIns,
(SELECT MAX(_Checkins.created)
FROM _Checkins
WHERE _Checkins.memberId = _Members.ID
AND _Checkins.created < _FilteredCheckins.lastCheckin) AS previousCheckin
FROM _Members
JOIN (SELECT memberId, COUNT(*) AS checkIns, MAX(created) AS lastCheckin
FROM _Checkins
WHERE created >= NOW() - INTERVAL 30 DAY
GROUP BY memberId
HAVING lastCheckin >= NOW() - INTERVAL 2 HOURS) _FilteredCheckins
ON _FilteredCheckins.memberId = _Members.ID
ORDER BY _FilteredCheckins.checkIns ASC
_Checkins.id
is unique (it should be), so COUNT(DISTINCT ID)
can be simplified to COUNT(*)
. _Checkins.id
是唯一的(应该是),所以COUNT(DISTINCT ID)
可以简化为COUNT(*)
。 If this isn't the case you'll need to put it back. (Side note: please don't use BETWEEN
, especially with date/time types ) (旁注:请不要使用
BETWEEN
, 尤其是日期/时间类型 )
(humorous side note: I keep mentally reading this as "chickens"....) (幽默的旁注:我一直在脑子里把它读作“鸡”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.