I've dealt with this a few times, here's my take on it.
My table looks like this:
CREATE TABLE visitors (
userid int,
visitorid int,
last_visit datetime,
primary key(userid, visitorid),
index(visitorid)
index(userid, last_visit)
) engine = memory;
Inserting data:
INSERT INTO visitors (userid, last_visit) VALUES ( 50, now() )
ON DUPLICATE KEY UPDATE last_visit = now();
Selecting:
select * from visitors WHERE userid=10 order by last_visit limit 10; # or whatever you need
Occasionally purge the table
DELETE from visitors WHERE last_visit > date_add(now(), INTERVAL -1 WEEK);
This is the way to go for a few reasons.
- You're using an in memory table, so you never touch disk.
- Index is on (visitorid, last_update), so it's pure index lookup. Very fast. Even without it, it should be fast.
- Pulling users via a separate query will let you cache them, but in theory they should be cached already if they've visited the site recently. Even if you aren't using cache, an in() query on user (primary key) should be very fast.
You can run a cron to backup this table once a minute
SELECT * from visitors INTO OUTFILE "/tmp/visitors.txt"