mysql中json数据存varchar与json类型对于简单查询效率的影响与朋友讨论⼀些简单json存储的问题,产⽣了测试这⼀问题的想法,测试准备如下:
1.两张表,分别如下,只有涉及到json字段的类型不同
CREATE TABLE `json_test` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int DEFAULT NULL,
`content` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
`iamge` json DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=520303 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
CREATE TABLE `varchar_test` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int DEFAULT NULL,
`content` varchar(10) COLLATE utf8mb4_general_ci DEFAULT NULL,
`image` varchar(1000) COLLATE utf8mb4_general_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=500001 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
2.两张表分别通过相同的⽅式进⾏批量插⼊,制造50w数据,每个userid都有100条数据,共5000个userid,⽣成的json数据内容如下:["blog.csdn/gushaolin/article/details/103546517", "blog.csdn/gushaolin/article/details/103546517",
"blog.csdn/gushaolin/article/details/103546517", "blog.csdn/gushaolin/article/details/103546517",
"blog.csdn/gushaolin/article/details/103546517", "blog.csdn/gushaolin/article/details/103546517",
"blog.csdn/gushaolin/article/details/103546517", "blog.csdn/gushaolin/article/details/103546517",
"blog.csdn/gushaolin/article/details/103546517", "blog.csdn/gushaolin/article/details/103546517"]
3.由于数据库在云服务器上,为了减少⽹络延迟对查询的影响,写⼀个api放在服务器上,通过计算查询时间差的⽅式来进⾏⽐较,并且api 调⽤数据库使⽤127.0.0.1,避免查询⾛⽹关,代码:
Map<String, Object> map = new HashMap<>();
LocalDateTime start = w();
List<JsonTest> list1 = jsonTestService.list(
new QueryWrapper<JsonTest>().lambda()
.eq(JsonTest::getUserId, 1)
);
LocalDateTime jsonEnd = w();
map.put("1", Duration.between(start, jsonEnd).toMillis());
LocalDateTime start2 = w();
List<VarcharTest> list2 = varcharTestService.list(
new QueryWrapper<VarcharTest>().lambda()
.eq(VarcharTest::getUserId, 1)
);
LocalDateTime varcharEnd = w();
mysql中selectmap.put("2", Duration.between(start2, varcharEnd).toMillis());
两种查询⽅式都是类似select * from table_name where user_id=1的查询⽅式,避免查询条件不同产⽣误差
4.通过请求接⼝,⽐较响应中1、2的毫秒时间差,经过⽐较,两种查询的时间差不太稳定,互有快慢,通过20次左右查询平均值⽐较,两种查询⽅式实际耗时基本相同,所以通过简单的索引查询带json类型的数据,并不会拖慢查询速度
结论:使⽤索引字段进⾏普通的数据查询带出json数据,效率与varchar类型基本⼀致,在业务中进⾏存储且不进⾏使⽤json类型的字段查询的场景下,是⼀个⾮常合适的⽅案,可以提升系统拓展性
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论