您现在的位置: 万盛学电脑网 >> 程序编程 >> 数据库 >> mssql数据库 >> 正文

MySQL在有索引列情况下select *的输出结果顺序

作者:佚名    责任编辑:admin    更新时间:2022-06-22

  创建一个表格,一个是主键列,一个是索引列。然后插入一批数据,调用select * from test_b,可以发现输出结果并没有按照Id有序,而是按照Type有序。

  如果希望按照Id有序,可以使用force index (primary)这一hint语句。

  mysql> CREATE TABLE `test_b` (

  -> `Id` int(11) NOT NULL,

  -> `Type` int(11) DEFAULT NULL,

  -> PRIMARY KEY (`Id`),

  -> KEY `IDX_Type` (`Type`)

  -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  Query OK, 0 rows affected (0.20 sec)

  mysql> insert into test_b values(1,1),(2,6),(3,2),(7,3),(4,1);

  Query OK, 5 rows affected (0.09 sec)

  Records: 5 Duplicates: 0 Warnings: 0

  mysql> select * from test_b;

  +----+------+

  | Id | Type |

  +----+------+

  | 1 | 1 |

  | 4 | 1 |

  | 3 | 2 |

  | 7 | 3 |

  | 2 | 6 |

  +----+------+

  5 rows in set (0.03 sec)

  mysql> select * from test_b force index (primary);

  +----+------+

  | Id | Type |

  +----+------+

  | 1 | 1 |

  | 2 | 6 |

  | 3 | 2 |

  | 4 | 1 |

  | 7 | 3 |

  +----+------+

  5 rows in set (0.00 sec)

  观察select * from test_b的前两条结果:(1,1),(4,1),当Type相等的时候,按照Id排序。为了确认这一点,再多插入点数据观察,结论相同。

  mysql> insert into test_b values(9,3),(6,3),(10,3);

  Query OK, 3 rows affected (0.04 sec)

  Records: 3 Duplicates: 0 Warnings: 0

  mysql> select * from test_b ;

  +----+------+

  | Id | Type |

  +----+------+

  | 1 | 1 |

  | 4 | 1 |

  | 3 | 2 |

  | 6 | 3 |

  | 7 | 3 |

  | 9 | 3 |

  | 10 | 3 |

  | 2 | 6 |

  +----+------+

  8 rows in set (0.00 sec)

  默认情况下为什么会结果按照索引列有序呢?这还要从数据库内部的运行机制说起。首先系统会查询索引表(test_b_indexed_type),该索引表的主键是索引列type(通常为了保证主键唯一性,type后面会添加一个id后缀),通过索引列查到Id,然后拿着这些Id去test_b中查询最终结果。为了最高效,扫描索引表的时候会顺着type主键往下扫,然后拿扫得的id去“逐个”请求test_b,于是自然就出现了按照索引列有序的结果。

  当Type列的值一致的时候,插入到索引列的数据可以根据Id顺序插入到索引表中,保证了当Type一致的时候,会按照Id排序。