select * 和 select 字段的速度对比

时间:2023-03-08 20:55:22

拿WordPress的数据库做一个对比

SELECT ID,post_title, post_author FROM wp_posts ORDER BY ID LIMIT 100;
OK, Time: 0.023000s SELECT * FROM wp_posts ORDER BY ID LIMIT 100;
OK, Time: 0.261000s SELECT `ID` , `post_author` , `post_date` , `post_date_gmt` , `post_content` , `post_title` , `post_excerpt` , `post_status` , `comment_status` , `ping_status` , `post_password`, `post_name` , `to_ping` , `pinged` , `post_modified` , `post_modified_gmt`, `post_content_filtered`, `post_parent` , `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count` FROM wp_posts ORDER BY ID LIMIT 100;
OK, Time: 0.231000s

总结

  1. 字段更少速度更快
  2. 没有大内容字段查询速度更快,有大内容字段的表需要最优速度时,可以写明 select 的字段来排除大内容字段
  3. select * 和 select 全部字段的查询速度相差不大

select * 的缺点

  1. select * 不能有效的利用覆盖索引
  2. select * 读取不需要的列会增加CPU、IO、NET消耗

覆盖索引

覆盖索引就是从索引中直接获取查询结果,要使用覆盖索引需要注意select查询列包含在索引列中;where条件包含索引列或者复合索引的前导列