1

I've got a table user_log where I store information about user activity, for example login and logout actions. Table has four colums: id, user_id, action and timestamp

I would like to select all logout and login actions timestamps for some user_id in one result table, there would be columns like this:

user_id login_timestamp logout_timestamp.

I use this MySQL query:

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

But the result contains duplicates of login_timestamp. Have a look: enter image description here

3
  • 1
    Yes because you have more than one logout_timestamp for user_id = 4. Commented Mar 6, 2016 at 9:58
  • @MotoGP I have the same amount of login and logout timestamps. Select Distinct using with () gives me syntax error, but without brackets I've got the same issue as posted. Commented Mar 6, 2016 at 10:03
  • i think you would get a cross joined result for login and logout timestamp for a given user. You need to add more filter conditions. Commented Mar 6, 2016 at 10:03

1 Answer 1

1

I can suggest another approach, a correlated query in the select :

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'

This will basically select the next logout for each login and will be faster then selecting from the table 3 times.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.