It is 04.17 in the morning and i cant figure what is wrong! Help please!
I have table with such columns in table user_logs:
id | user_id | action | reference | time
----------------------------------------
1 | 1 | login | 0 | 1333800404
2 | 1 | logout | 1 | 1333800424
3 | 1 | login | 0 | 1333800434
4 | 1 | logout | 3 | 1333800444
And query:
SELECT reference r,
sum(time-(SELECT time FROM users_logs WHERE id = r)) time_of_logon
FROM users_logs
WHERE user_id = 1 AND action = 'logout'
Unfortunately sum() function returns unexpected value.
If I remove sum() I get such a query:
SELECT reference r,
(time-(SELECT time FROM users_logs WHERE id = r)) time_of_logon
FROM users_logs
WHERE user_id = 1 AND action = 'logout'
and result:
r | time_of_logon
-----------
1 | 20
3 | 10
As expected - i printed all rows with action 'logout' of user_id = 1 decrementing time of logoff from time i got from subquery (time of login connected with logout). Now i have time user was logged in. So far so good. Now, when I add sum (like in first query) I would expect sum of time_of_logon (should be 30). If I put avg function instead of sum i would expect 15 ((10+20)/2).
Sum version: I get 60, avg version - i get 30.
Type of 'time' field is integer.
My guessing: I guess that mysql somehow returns not 2 rows as it shows but it's working on 4 rows, or doubles some calculations beneath the main query. Because both - avg and sum result is twice as big as it should be.
Maybe it's the time issue that my brain is not working anymore but i cant figure out what is wrong. Please help.