从MySQL表中获取下一个空闲ID的最短方法是什么?

Mis*_*hko 0 php mysql

我有一张带id柱子的桌子.ids按升序排列,但不一定是连续的.例如:1,2,3,5,6,10,11,12

我需要找到下一个"free"id,即max(id)+ 1(如果表为空,则为1).

目前我在PHP中这样做:

function get_free_id($con) {
    $sql = "SELECT MAX(id) AS last_id FROM Table";
    $last_id_query = mysql_query($sql, $con);
    $last_id_result = mysql_fetch_array($last_id_query);
    $last_id = $last_id_result['last_id'];  
    return ($last_id == NULL) ? 1 : ($last_id + 1);
}
Run Code Online (Sandbox Code Playgroud)

我觉得这个功能对于这个简单的任务来说"太长了",并且可以做得更简单.

我对吗 ?怎么样 ?

You*_*nse 7

没有保证的方式.
所以,你不应该这样做.

首先创建一个记录,获取自动生成的id,然后在你想要的地方使用它.