我有一个包含50行的表,id
列作为主键,自动增量。
起始id
值,其中1 - 50;
删除行(例如id=1
)并插入新行后,会有id=51
。
如何将新行设置为第一个空位,本例id=1
自动{而不是51
;
如果删除id=5
,则下一个插入的行应为id=5
,依此类推。
答案 0 :(得分:2)
使用自动增量列时,您无法更改每行的键检查 您可以禁用密钥检查并截断将为每行重新分配新密钥(数字)的表,但这意味着先前的密钥将移动到其他行,具体取决于删除的行数以及它们在序列中的位置。
如果你真的需要做一些像你正在做的事情,你可以创建一个虚假的索引" auto"您的脚本增加了列。然后,您就可以以您选择的任何方式管理该列。
答案 1 :(得分:1)
您可以使用MySQL的查询变量来跟踪先前的ID并计算查询中的差异,例如:
$accesses = DB::table('accesses')
->select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->where('state','=','Assigned');
$all = DB::table('reports')
->select(array('id', 'fullname','emp_id','shift','state','resolved_at', 'closed_at','assigned_to'))
->union($accesses)
->where('state', '=', 'Assigned')
->get();
$open_tickets = Charts::database($all, 'bar', 'highcharts')
->title("Open Tickets (Assigned)")
->elementLabel("Total Assigned Tickets")
->dimensions(1000, 500)
->responsive(false)
->groupBy('assigned_to')
->labels($all->assigned_to->name);
//users migration
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('emp_id');
$table->string('shift');
$table->string('name');
$table->string('email')->unique();
$table->string('contact')->nullable();
$table->string('password');
$table->string('role')->default('admin');
$table->rememberToken();
$table->timestamps();
});
//reports migration
Schema::create('reports', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->nullable();
$table->string('fullname');
$table->string('emp_id');
$table->string('shift');
$table->longText('report');
$table->string('status')->default('Pending'); //Pending, Approved
$table->string('state')->default('Open'); //Open, Assigned, Resolved, Closed
$table->date('resolved_at')->nullable();
$table->date('closed_at')->nullable();
$table->integer('assigned_to')->nullable();
$table->longText('action')->nullable();
$table->timestamps();
});
//accesses migration|
Schema::create('accesses', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->nullable();
$table->string('fullname');
$table->string('emp_id');
$table->string('shift');
$table->string('request');
$table->longText('note')->nullable();
$table->string('status')->default('Pending'); //Pending, Approved
$table->string('state')->default('Open'); //Open, Assigned, Resolved, Closed
$table->date('resolved_at')->nullable();
$table->date('closed_at')->nullable();
$table->integer('assigned_to')->nullable();
$table->longText('action')->nullable();
$table->timestamps();
});
这会给你所有有差异的ID。然后,您可以将其包装到另一个查询中,SELECT id, id - @previous AS difference, @previous := id
FROM test, (SELECT @previous := 0) a
ORDER BY id;
包含差异的行> 1获取可用的id,例如:
SELECT
这里是 SQL Fiddle 。