MySQL 函数, 效率不怎么样啊~
by adie
2010-11-22 14:07:13
delimiter //
CREATE FUNCTION isActiveUser(name VARCHAR(64)) RETURNS INT
BEGIN
DECLARE sdate DATETIME;
DECLARE edate DATETIME;
DECLARE ret INT DEFAULT 0;
SELECT updatedate INTO sdate FROM userinfo WHERE username = name;
WHILE sdate < NOW() DO
SET edate = ADDDATE(sdate, INTERVAL 2 day);
SELECT count(*) INTO ret FROM radacct WHERE
(acctstarttime < sdate AND acctstoptime > sdate) OR
(acctstarttime > sdate AND acctstarttime < edate);
SET sdate = edate;
IF ret = 0 THEN
RETURN 0;
END IF;
END WHILE;
RETURN 1;
END
//
delimiter ;
mysql> select count(*) from
-> (select username from radacct where
-> (acctstoptime is null or acctstoptime > subdate(now(), interval 2 day))
-> and username not like 'www.evovpn.com' group by username
-> ) a, userinfo where a.username = userinfo.username and
-> (userinfo.updatedate > subdate(now(), interval 2 day) or isActiveUser (a.username));
+----------+
| count(*) |
+----------+
| 264 |
+----------+
1 row in set (28.17 sec)
mysql> select count(*) from
-> (select username from radacct where
-> (acctstoptime is null or acctstoptime > subdate(now(), interval 2 day))
-> and username not like 'www.evovpn.com' group by username
-> ) a, userinfo where a.username = userinfo.username and
-> ( (to_days(now()) - to_days(userinfo.updatedate)) / 2 <
-> (select count(*) from radacct where radacct.username = a.username)
-> );
+----------+
| count(*) |
+----------+
| 236 |
+----------+
1 row in set (0.06 sec)
▲评论