表设计(天气信息表)
DROP TABLE IF EXISTS `city_weather_data`;
CREATE TABLE `city_weather_data` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键',
`city_id` varchar(20) DEFAULT NULL COMMENT '城市id',
`weather_condition` varchar(20) DEFAULT NULL COMMENT '天气状况)',
`temp` varchar(10) DEFAULT NULL COMMENT '温度',
`wind_level` varchar(10) DEFAULT NULL COMMENT '风级',
`updatetime` varchar(20) DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `cityId_updatetime_unique` (`city_id`,`updatetime`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=58 DEFAULT CHARSET=utf8;
其中,设置唯一索引:保证当 city_id
和 updatetime
均相同时的唯一性
测试插入sql
insert into city_weather_data (city_id,weather_condition,temp, wind_level,updatetime)
values ('1101', '多云','34','3','2018-02-27 12:10:00')
执行两次,第一次成功,第二次报错:
Error : Duplicate entry 'city_id-updatetime' for key 'cityId_updatetime_unique'
若这段是利用mybatis
进行数据的插入,第二次执行时,将会抛出org.springframework.dao.DuplicateKeyException
异常。
执行计划
explain
select
t.id, t.city_id, t.weather_condition, t.temp, t.wind_level, t.updatetime
from city_weather_data t
where t.city_id = '1101' and t.updatetime between '2018-02-26 18:40:00' and '2018-02-27 12:20:00';
返回信息:
type = range
另外:between
是闭区间,eg:返回的数据包含 2018-02-26 18:40:00
和 2018-02-27 12:20:00