3

这个问题与我的旧问题Getting last record from mysql有点相关。

根据这些答案,我了解到SELECT 不能保证以任何特定顺序返回行(当然,不使用 ORDER BY 子句)。

我遵循@YaK 的答案并AUTO_INCREMENT使用以下命令在表中添加。

ALTER TABLE maxID ADD sequence INT DEFAULT NULL;
ALTER TABLE maxID ADD INDEX(sequence);
ALTER TABLE maxID MODIFY sequence INT AUTO_INCREMENT;

然而今天我有一个问题。

什么时候SELECT不能保证以任何特定顺序返回行(ORDER BY当然不使用子句),那么在更改表时,AUTO_INCREMENT会正确实现吗?

4

1 回答 1

1

Depends on Engine type for what is happening in the background:

'For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. In this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix. This is useful when you want to put data into ordered groups.'

This will create tables with multiple values on the auto_increment, non-unique values.

So what you really mean is to have a PRIMARY KEY with auto_increment (though not necessary) for InnoDB tables. A simple select will return values in the Primary Key order when selecting without a order by clause because it is stored in this order and will use the Primary Key for sorting.

If you want a specific order ALWAYS specify it, use the PRIMARY KEY if you want, but ALWAYS specify it.

于 2012-11-12T16:39:50.247 回答