我想计算特定用户在给定日期和之前召开会议的连续 N 天。
例如:计算 id 为 1 的用户在 2013 年 1 月 16 日的连续会议天数。
我在这里和这里找到了一些很好的答案,但是表格不像我上面的示例那样采用正常形式,我无法弄清楚如何为我的场合实施它。
一个示例表结构如下:
CREATE TABLE IF NOT EXISTS `meetings` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `meetings_users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(10) unsigned NOT NULL,
`meeting_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `meeting_id` (`meeting_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Constraints for table `meetings_users`
--
ALTER TABLE `meetings_users`
ADD CONSTRAINT `meetings_users_ibfk_2` FOREIGN KEY (`meeting_id`) REFERENCES `meetings` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `meetings_users_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
样品插入
INSERT INTO `users` ( `id` ) VALUES (1)
INSERT INTO `meetings` ( `id`, `time` ) VALUES
(1, '2013-01-14 10:00:00'),
(2, '2013-01-15 10:00:00'),
(3, '2013-01-16 10:00:00')
INSERT INTO `meetings_users` ( `id`, `meeting_id`, `user_id` ) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 1)
期望的输出:
*+---------+-----------------+
| user_id | consecutive_days |
+---------+------------------+
| 1 | 3 |
+---------+------------------+