in reply to Counting events and getting top 5 matches

Let's see ... I've just recently done something similar... in pure SQL. (Well, there may be some DB2-isms here, but you don't specify your DB vendor.)

WITH T AS (SELECT U.NICK, COUNT(*) AS TOTAL, R.REFERREDNODE FROM REFERU R, USER U WHERE R.REFERREDNODE IS NOT NULL AND R.REFERREDNODE = U.NODEID AND NODEID > 0 AND VISIBLE = 'Y' GROUP BY U.NICK, R.REFERREDNODE ORDER BY COUNT(*) DESC FETCH FIRST 5 ROWS ONLY), U AS (SELECT T.NICK AS NICK, MAX(R.MSGID) AS MAXID, MIN(R.MSGID) AS MINID FROM USER, T, LOGS L, REFERU R WHERE T.REFERREDNODE = R.REFERREDNODE AND R.MSGID = L.MSGID AND USER.NICK = L.FROM AND VISIBLE = 'Y' AND NODEID > 0 GROUP BY T.NICK) SELECT T.NICK, T.TOTAL, LMAX.FROM, LMIN.FROM FROM T, U, LOGS LMAX, LOGS LMIN WHERE U.MAXID = LMAX.MSGID AND U.MINID = LMIN.MSGID AND T.NICK = U.NICK ORDER BY T.TOTAL DESC, U.MAXID DESC
A couple of subselects ... had it been my intention to get out these stats rather than learn SQL, I probably would have just queried for the counts, and then resolved individual items later in other queries. It might have been easier on the db, too, because there'd be far fewer joins. But I still would have got the db to do the counting for me - just to keep the data transfer down, and because the db is probably faster at it than perl.

PS - I don't actually have that much data hard-coded, I just didn't want to show the binding. That said, the values are static, the query isn't reused with other values, so leaving them in the query probably isn't a bad thing anyway.

PPS - I realise this doesn't directly answer your question - but may give you just another way to look at it.