我正在使用MySQL和Visual Basic开发一个登录/退出表单。我现在的查询只显示每个用户的最新事件,但我希望显示前两个事件(即:他/她何时登录以及何时退出。
我有一个名为event
的表,其中包含以下字段:
Event_ID
User_BannerID
Class_ID
Timestamp
Status
Creator
SELECT CONCAT(u.lastname, ', ', u.firstname) AS Name
, s.class AS Class
, DATE_FORMAT(e.timestamp,'%b %d %Y - %r') AS DateTime
, e.status AS Status
FROM event e, user u, status s
WHERE e.user_bannerid = u.user_bannerid
AND e.class_id = s.class_id
AND event_id IN
(
SELECT MAX(event_id)
FROM event e
GROUP BY e.user_bannerid
)
ORDER BY name
答案 0 :(得分:0)
在SELECT语句中使用LIMIT子句并结合正确的ORDER BY:
SELECT ...
FROM theTable
WHERE ...
LIMIT 2
ORDER BY timestamp DESC
答案 1 :(得分:0)
查看this article中名为“从每个组中选择前N行”的部分。
答案 2 :(得分:0)
AND event_id IN
(
SELECT event_id
FROM (SELECT * FROM event ORDER BY event_id DESC LIMIT 2) e
)
变通方法的来源:http://forums.mysql.com/read.php?86,14788,14788及其回复,链接在底部。测试5.1