我正在设计一个全新的数据库。每天都会有很多疑问。它实际上是一个非常非常简单的计时系统,但我仍然希望尽可能快。我自己正在构建它,因为我可以,而且我可以节省大量资金,同时获得我想要的东西,只是为了掌握我在不同项目中消耗的时间。
CREATE TABLE IF NOT EXISTS `activity` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`activity_date` date NOT NULL,
`minutes` int(11) NOT NULL COMMENT 'time for this activity (in minutes)
`week_nr` tinyint(2) unsigned NOT NULL COMMENT 'store weeknr for faster selection',
`year_nr` smallint(4) unsigned NOT NULL COMMENT 'store yearnr for fast selection',
`month_nr` tinyint(2) unsigned NOT NULL COMMENT 'store monthnr for faster selection',
PRIMARY KEY (`id`),
KEY `week_nr` (`week_nr`),
KEY `year_nr` (`year_nr`),
KEY `month_nr`, (`month_nr`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci COMMENT='Table for storing activities' AUTO_INCREMENT=1 ;
当用户在上表中保存活动时,我的想法是更新 year_nr , week_nr 和 month_nr 在activity_date中,系统可以轻松获取活动报告,例如第5周和第10周,或第5个月(5月)和第10个月(10月)之间的活动。
这是一个好主意还是更好的只是在日期字段上放一个索引?我的预测是,会有更多的选择查询继续进行,然后就是更新。
答案 0 :(得分:1)
考虑到以下提示,答案很简单:
将连续句点的查询写为显式范围条件。
2013年至2014年的例子:
WHERE activity_date >= '2013-01-01' and activity_date < '2015-01-01'
您需要做的就是计算边界日期,然后使用此模式。此模式可以在activity_date
上使用直接索引 - 不需要其他列/索引。只要您需要查询连续的一段时间(而不是“每个星期一”,这是分散的时间段),它就可以工作。
不要将任何函数应用于索引列。不要YEAR(activity_date)
这是要避免的反模式:)
参考:http://use-the-index-luke.com/sql/where-clause/obfuscation/dates
答案 1 :(得分:0)
我认为这是一个坏主意。您应该在日期字段上构建索引而不是..