SQL关联查询关联字段数据类型不一致导致耗时过长

SQL关联查询消耗662ms

select count(*) from p_video_circle_relation a 
	left join p_video_info b 
	on a.video_id = b.work_id 
	where a.circle_id = 212307047;

最先想到的是表没有创建索引

mysql> desc p_video_circle_relation;
+-------------+------------+------+-----+---------+----------------+
| Field       | Type       | Null | Key | Default | Extra          |
+-------------+------------+------+-----+---------+----------------+
| id          | int(11)    | NO   | PRI | NULL    | auto_increment |
| video_id    | bigint(20) | YES  | MUL | NULL    |                |
| circle_id   | bigint(20) | YES  | MUL | NULL    |                |
+-------------+------------+------+-----+---------+----------------+
3 rows in set

mysql> desc p_video_info;
+---------------+---------------+------+-----+---------+----------------+
| Field         | Type          | Null | Key | Default | Extra          |
+---------------+---------------+------+-----+---------+----------------+
| id            | int(11)       | NO   | PRI | NULL    | auto_increment |
| api_id        | bigint(20)    | YES  |     | NULL    |                |
| video_name    | varchar(100)  | NO   |     | NULL    |                |
| work_id       | varchar(50)   | YES  | UNI | NULL    |                |
+---------------+---------------+------+-----+---------+----------------+
4 rows in set

必要字段都已添加索引,并且数据量并不大

mysql> select count(id) from p_video_circle_relation;
+-----------+
| count(id) |
+-----------+
|    260021 |
+-----------+
1 row in set

mysql> select count(id) from p_video_info;
+-----------+
| count(id) |
+-----------+
|    260030 |
+-----------+
1 row in set

仔细观察发现关联字段video_id和work_id的数据类型并不一致,video_id是bigint类型,work_id是varchar类型,关联查询时必须将关联字段转换成相同的类型才能进行比较,数据越多,转换需要的时间越长,将work_id修改为bigint类型后,查询仅需13ms

猜你喜欢

转载自blog.csdn.net/a19881029/article/details/81227623