Mysql:如何从包含开始和结束日期的表中获取开始日期和结束日期之间的每一天的结果?

时间:2016-07-11 10:54:31

标签: mysql sql database join stored-procedures

我有开始日期和结束日期。对于开始日期和结束日期之间的每一天,我都希望得到一个结果,即使我的统计表中没有结果。

解决此问题的最佳建议是为每个日期(日期)创建临时表的存储过程,以便我可以创建连接。

BEGIN

    declare d datetime;
    create temporary table joindates (d date not null);

    SET d = fkstartdate;

    WHILE d <= fkenddate DO

        insert into joindates (d) values (d);
        set d = date_add(d, interval 1 day);

    END WHILE;


SELECT * FROM `joindates` AS tempt LEFT JOIN `radacct` AS stats 
ON stats.acctstarttime <= tempt.d AND (stats.acctstoptime >= tempt.d OR stats.acctstoptime IS NULL) AND calledstationid = calledstationid 
ORDER BY tempt.d ASC;

    drop temporary table joindates;

END

现在尚未最终确定连接(仅用于测试)。但正如你所看到的,如果&#34; radacct&#34; table只使用一个日期col。我可以通过使用=运算符来轻松创建JOIN。

现在&#34; radacct&#34;但是对于那些条目使用acctstarttime和acctstoptime(我无法修改此表,由radius服务器给出)都是日期时间类型。

因此,在我的查询中,我需要在开始日期和停止日期之间的所有条目,其中acctstarttime在过去或在我的时间段内开始。并且acctstoptime在我的时间段内,在我的时间段之后或NULL(活动会话)。

我的JOIN解决方案的问题:它的速度很慢 你有什么更快的查询想法吗?

由于

附录1:非常重要的是,即使acctstarttime到acctstoptime超过多天,我每天的每个条目都会得到与我的日期相匹配的结果。这样我总能让所有用户上网。

附录2: 根据要求,&#34; radacct&#34;的全表结构 - freeradius MySql模块的会计表......

CREATE TABLE `radacct` (
 `radacctid` bigint(21) NOT NULL AUTO_INCREMENT,
 `acctsessionid` varchar(64) NOT NULL DEFAULT '',
 `acctuniqueid` varchar(32) NOT NULL DEFAULT '',
 `username` varchar(64) NOT NULL DEFAULT '',
 `groupname` varchar(64) NOT NULL DEFAULT '',
 `realm` varchar(64) DEFAULT '',
 `nasipaddress` varchar(15) NOT NULL DEFAULT '',
 `nasportid` varchar(15) DEFAULT NULL,
 `nasporttype` varchar(32) DEFAULT NULL,
 `acctstarttime` datetime DEFAULT NULL,
 `acctstoptime` datetime DEFAULT NULL,
 `acctsessiontime` int(12) unsigned DEFAULT NULL,
 `acctauthentic` varchar(32) DEFAULT NULL,
 `connectinfo_start` varchar(50) DEFAULT NULL,
 `connectinfo_stop` varchar(50) DEFAULT NULL,
 `acctinputoctets` bigint(20) DEFAULT NULL,
 `acctoutputoctets` bigint(20) DEFAULT NULL,
 `calledstationid` varchar(50) NOT NULL DEFAULT '',
 `callingstationid` varchar(50) NOT NULL DEFAULT '',
 `acctterminatecause` varchar(32) NOT NULL DEFAULT '',
 `servicetype` varchar(32) DEFAULT NULL,
 `framedprotocol` varchar(32) DEFAULT NULL,
 `framedipaddress` varchar(15) NOT NULL DEFAULT '',
 `acctstartdelay` int(12) unsigned DEFAULT NULL,
 `acctstopdelay` int(12) unsigned DEFAULT NULL,
 `xascendsessionsvrkey` varchar(10) DEFAULT NULL,
 PRIMARY KEY (`radacctid`),
 UNIQUE KEY `acctuniqueid` (`acctuniqueid`),
 KEY `username` (`username`),
 KEY `framedipaddress` (`framedipaddress`),
 KEY `acctsessionid` (`acctsessionid`),
 KEY `acctsessiontime` (`acctsessiontime`),
 KEY `acctstarttime` (`acctstarttime`),
 KEY `acctstoptime` (`acctstoptime`),
 KEY `nasipaddress` (`nasipaddress`)
) ENGINE=InnoDB AUTO_INCREMENT=2041894 DEFAULT CHARSET=latin1 

0 个答案:

没有答案