我有一个表 user_log ,其中我存储有关用户活动的信息,例如登录和注销操作。 表格有四个列: ID , user_id ,操作和时间戳
我想在一个结果表中选择一些 user_id 的所有注销和登录操作时间戳,会有如下列:
user_id login_timestamp logout_timestamp 。
我使用这个MySQL查询:
SELECT
user_log.user_id,
user_log_login.login_timestamp,
user_log_logout.logout_timestamp
FROM
user_log
INNER JOIN
(SELECT
user_id, timestamp as login_timestamp
FROM
user_log
WHERE
action = 'login successful') as user_log_login
ON
user_log.user_id = user_log_login.user_id
INNER JOIN
(SELECT
user_id, timestamp as logout_timestamp
FROM
user_log
WHERE
action = 'logout successful') as user_log_logout
ON
user_log.user_id = user_log_logout.user_id
WHERE
user_log.user_id = 4
答案 0 :(得分:1)
我可以建议另一种方法,即选择中的相关查询:
SELECT t.user_id,t.timestamp Login_Time ,
(SELECT s.timestamp FROM user_log s
WHERE s.user_id = t.user_id and s.action = 'logout successful'
AND s.timestamp > t.timestamp
ORDER BY s.timestamp limit 1) as Logout_Time
FROM user_log t
WHERE t.user_id = 4
AND t.action = 'login successful'
这基本上会为每次登录选择下一次注销,并且会比从表中选择3次更快。