Table design for users presence?
In a chat room I have a bot that will collect information such as when a person joins or leave and fill up a database where I would like to have statistics of how long people usually stay and which rooms, etc.
Not reflecting so much I've done the follow table:
CREATE TABLE IF NOT EXISTS `users_login_logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL,
`username` varchar(16) NOT NULL,
`room_id` int(11) NOT NULL DEFAULT '0',
`action` tinyint(1) NOT NULL DEFAULT '0',
`ip` int(10) unsigned NOT NULL DEFAULT '0',
`ts_register` timestamp NOT NULL DEFAULT CURRE开发者_运维技巧NT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
action is either 0 for entering the room and 1 to leaving.
After some running It doesnt seem that this layout is the best one for what I want, for example calculating when the user entered / left would be a bit confusing and could produce wrong results if for example for w/e reason the bot does not record or miss any data.
What could I do to make this layout more reliable for quering the users presence to retrieve the amount of hours, dayly, weekly and month the users are in the room X for example ?
I would create something along the lines of:
id - primary key
user_id - foreign key
room_id - foreign key
time_entered - timestamp
time_left - timestamp
(other fields as needed)
On a user's signin, create a new record with a NULL
time_left
, on a user's signout, update the record and store the time_left
. When your application starts, look for any records with a NULL
time_left
- that would signify the app crashed/missed some exits and needs to close them out (however you want to handle that).
You could get a list of who was in the room by WHERE time_left IS NULL
, and calculating how long a user was online is trivial.
精彩评论