鉴于此表:
mysql> describe activity;
+---------------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------------+-------------+------+-----+---------+-------+
| user_id | varchar(16) | NO | | NULL | |
| login_time | int(11) | NO | | NULL | |
| last_activity_time | int(11) | NO | | NULL | |
| last_activity_description | text | YES | | NULL | |
| logout_time | int(11) | NO | | NULL | |
+---------------------------+-------------+------+-----+---------+-------+
5 rows in set (0.01 sec)
我想为每个登录的用户选择最新的last_activity_time
(标准Unix时间戳)(即有一行或多行logout_time
不是zer0)。
我试过
SELECT user_id, login_time, MAX(last_activity_time)
FROM activity
WHERE logout_time="0";
...但是只找到一个有两个用户登录的条目,可能是因为我选择了MAX(last_activity_time)
我想要的是像
SELECT all unique user_ids
SELECT each of those which has one or more entries where `logout_time` != 0
SELECT the maximum value of `logout_time` for each of those
所有在一个SELECT语句中。我怎样才能做到这一点?
答案 0 :(得分:3)
SELECT user_id, MAX(logout_time)
FROM activity
WHERE logout_time <> "0"
GROUP BY user_id;