mysql主键自增的表是按照主键自增排序吗?
-
原表数据,可以看出是自增的顺序
-
执行sql
select id from table
可以看出这里的结果,并非按照主键排序
思考:为什么mysql的排序不是按照主键排序的呢
官方回复:
https://forums.mysql.com/read.php?21,239471,239688#msg-239688
- Do not depend on order when ORDER BY is missing.
- Always specify ORDER BY if you want a particular order – in some situations the engine can eliminate the ORDER BY because of how it
does some other step.- GROUP BY forces ORDER BY. (This is a violation of the standard. It can be avoided by using ORDER BY NULL.)
大概意思是,如果没有orderby 不要依赖表中的顺序,可能是存在问题
猜想:
mysql的排序更多的是按照物理空间的顺序,例如我们数据表中插入了id为1-10的数据,此时我们删除1,然后插入11,那么此时物理顺序是什么?应该是2,3…,11,还是11,2,3…呢?这就需要看删除的1的空间是否能够容纳数据11的插入,如果能够,就会在原来1的空间上插入数据11,如果不能,就另辟新的空间插入11。
结论:如果是需要排序的话,一定要加一个order by