0

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.

4

2 に答える 2

1
SELECT user_id, sum(time_of_logon) as sum_login_time
FROM
(
  SELECT user_id,
         reference as r, 
         (time-(SELECT time FROM users_logs WHERE id = r)) as time_of_logon
  FROM users_logs 
  WHERE user_id = 1 AND action = 'logout'
) subtable
GROUP BY user_id

2段階のクエリを実行できますか?

于 2012-04-09T02:55:33.397 に答える
0

通常の結合を使用するだけです。

select t1.id as r, t2.time - t1.time as time_of_logon
from user_logs t1
join user_logs t2 on t2.reference = t1.id
where t1.action = 'login'
and t1.user_id = 1;

ログアウトのみがゼロ以外の参照値を持つため、表示されているもの以外に参加する必要はありません。実際にt1.action = 'login'は、同じ理由で必要ではありませんが、そのままにしておくことができます-パフォーマンスに少し役立つ可能性があります(テストする必要があります)

にインデックスがある場合、これもかなりうまく機能しますreference

于 2012-04-09T04:53:52.357 に答える