测试索引

测试索引

创建测试表1

-- 创建测试表
CREATE TABLE `app_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT '' COMMENT '用户昵称',
`email` varchar(50) NOT NULL COMMENT '用户邮箱',
`phone` varchar(20) DEFAULT '' COMMENT '手机号',
`gender` tinyint(4) unsigned DEFAULT '0' COMMENT '性别(0:男;1:女)',
`password` varchar(100) NOT NULL COMMENT '密码',
`age` tinyint(4) DEFAULT '0' COMMENT '年龄',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='app用户表'
 
--编写函数插入一百万条测试数据
DROP FUNCTION IF EXISTS mock_data;
DELIMITER $$
CREATE FUNCTION mock_data()
RETURNS INT
BEGIN
DECLARE num INT DEFAULT 1000000;
DECLARE i INT DEFAULT 0;
WHILE i < num DO
INSERT INTO app_user(`name`, `email`, `phone`, `gender`, `password`,`age`)
VALUES(CONCAT('用户', i), '24736743@qq.com', CONCAT('18', FLOOR(RAND()*(999999999-100000000)+100000000)),FLOOR(RAND()*2),UUID(),
FLOOR(RAND()*100));
SET i = i + 1;
END WHILE;
RETURN i;
END;
SELECT mock_data();
 
--编写函数插入6万条测试数据
DROP FUNCTION IF EXISTS mock_data;
DELIMITER $$
CREATE FUNCTION mock_data()
RETURNS INT
BEGIN
DECLARE num INT DEFAULT 60000;
DECLARE i INT DEFAULT 0;
WHILE i < num DO
INSERT INTO biz_custom_user
(`id`,`name`, `k_amount`,`type`, `stage_id`,`grade_id`,`mobile`, `tenant_id`,`area_id`,`city_id`,`province_id`,`saas_id`, `CREATED_BY`, `CREATED_DATE`,  `UPDATED_BY`, `UPDATED_DATE`)
VALUES(1934+i,CONCAT('test', i),'0',4,3,103,CONCAT('222000',lpad(i, 5, 0)),1886,'141002','141000','140000',1,'2','2024-01-02 15:29:09','2','2024-01-02 15:38:53');
SET i = i + 1;
END WHILE;
RETURN i;
END;
SELECT mock_data();
 

创建测试表2

1、创建一个名为 cus_order 的表,为了测试方便, cus_order 这张表只有 idscorename这 3 个字段。

CREATE TABLE `cus_order` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `score` int(11) NOT NULL,
  `name` varchar(11) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=100000 DEFAULT CHARSET=utf8mb4;

2、定义一个简单的存储过程(PROCEDURE)来插入 100w 测试数据。

DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `BatchinsertDataToCusOder`(IN start_num INT,IN max_num INT)
BEGIN
      DECLARE i INT default start_num;
      WHILE i < max_num DO
          insert into `cus_order`(`id`, `score`, `name`)
          values (i,RAND() * 1000000,CONCAT('user', i));
          SET i = i + 1;
      END WHILE;
  END;;
DELIMITER ;

3、存储过程定义完成之后,我们执行存储过程即可!

CALL BatchinsertDataToCusOder(1, 1000000); # 插入100w+的随机数据

等待一会,100w 的测试数据就插入完成了!

无索引查询

-- 查看耗时 0.595s 0.552s 0.557s
SELECT * FROM app_user WHERE name = '用户9999';

索引查询

CREATE INDEX name ON app_user(name);
 
-- 查看耗时 0.011s 0.012s 0.011s
SELECT * FROM app_user WHERE name = '用户9999';