This requires a self-join if you are to do it in MySQL. It's a pain in the neck to do a self-join because MySQL has no built in rownum function. But it's still doable.
First, we need to create a subquery to create a virtual table simulating SELECT rownum, user, timestamp FROM login
which we can do like this. http://sqlfiddle.com/#!2/bf6ef/2/0
SELECT @a:=@a+1 AS rownum, user, timestamp
FROM (
SELECT user, timestamp
FROM login
ORDER BY timestamp
) C,
(SELECT @a:=0) s
Next, we need to do a self-join of this virtual table to a copy of itself. What we want in this result set is a list of all the consecutive pairs of rows in the table. That query is a hairball -- it puts the structured in structured query language. But it works. Here it is: http://sqlfiddle.com/#!2/bf6ef/4/0
SELECT first.user AS fuser,
first.timestamp AS ftimestamp,
second.user AS suser,
second.timestamp as stimestamp,
TIMESTAMPDIFF(SECOND, first.timestamp, second.timestamp) AS timeloggedin
FROM (
SELECT @a:=@a+1 AS rownum, user, timestamp
FROM (
SELECT user, timestamp
FROM login
ORDER BY timestamp
) C,
(SELECT @a:=0) s
) AS first
JOIN (
SELECT @b:=@b+1 AS rownum, user, timestamp
FROM (
SELECT user, timestamp
FROM login
ORDER BY timestamp
) C,
(SELECT @b:=0) s
) AS second ON first.rownum+1 = second.rownum
The whole trick for comparing consecutive rows is the
SELECT (virtual_table) AS first
JOIN (virtual_table) AS second ON first.rownum+1 = second.rownum
query pattern. The rownum+1 = rownum thing gathers rows with consecutive row numbers together.
Next, we need to summarize the result of that query to get the total time logged in for each user. That will work like this:
SELECT user, SUM(timeloggedin) AS timeloggedin
FROM (
/* the self-joined query */
) AS selfjoin
GROUP BY user
ORDER BY user
That looks like this: http://sqlfiddle.com/#!2/bf6ef/5/0
This is the whole query put together.
SELECT user, SUM(timeloggedin) AS timeloggedin
FROM (
SELECT first.user AS user,
TIMESTAMPDIFF(SECOND, first.timestamp, second.timestamp) AS timeloggedin
FROM (
SELECT @a:=@a+1 AS rownum, user, timestamp
FROM (
SELECT user, timestamp
FROM login
ORDER BY timestamp
) C,
(SELECT @a:=0) s
) AS first
JOIN (
SELECT @b:=@b+1 AS rownum, user, timestamp
FROM (
SELECT user, timestamp
FROM login
ORDER BY timestamp
) C,
(SELECT @b:=0) s
) AS second ON first.rownum+1 = second.rownum
) AS selfjoin
GROUP BY user
ORDER BY user
It's not real intuitive for somebody used to procedural, algorithmic, thinking. But this is the way you do this kind of consecutive-row comparison in SQL.