简体   繁体   English

将唯一值插入 MySQL 表

[英]Insert a unique value to MySQL table

I have a table named leads with one column named id , it is not a primary key and not auto incremented.我有一个名为leads的表,其中有一列名为id ,它不是主键,也不是自动递增的。 I want to take the maximum id and increment it to insert new id.我想取最大 id 并增加它以插入新的 id。
This is my approach.这是我的方法。 (I do this for testing) (我这样做是为了测试)

<?php
for($i=1; $i<1000; $i++){

    \DB::beginTransaction();
    \DB::raw('LOCK TABLES leads WRITE');
    // Get maximum id
    $max = (int)\DB::table('leads')->max('id');

    \DB::table('leads')->insert([
        'id'=>str_pad(++$max, 10, '0', STR_PAD_RIGHT) // Make 10 digit id
    ]);

    \DB::raw('UNLOCK TABLES');
    \DB::commit();

}
?>

When I execute this code at once, the id does not being duplicate.当我一次执行此代码时,id 不会重复。 But when I hit this route from multiple browser at a time, the id gets duplicate.但是当我一次从多个浏览器点击这条路线时,id 会重复。 How can I resolve the problem without make the column AUTO_INCREMENT?如何在不使列 AUTO_INCREMENT 的情况下解决问题?

I suggest using AUTO_INCREMENT .我建议使用AUTO_INCREMENT but if you don't want you can insert multi record to avoid duplicate same as :但如果你不希望你可以插入多条记录以避免重复:

<?php

\DB::beginTransaction();
// Get maximum id
$max = (int)\DB::table('leads')->max('id');
\DB::raw('LOCK TABLES leads WRITE');
for($i=1; $i<1000; $i++){
    $data[] = [
        'id'=>str_pad(++$max, 10, '0', STR_PAD_RIGHT) // Make 10 digit id
    ]
}
\DB::table('leads')->insert($data);
\DB::raw('UNLOCK TABLES');
\DB::commit();
?>

I think it's best to use AUTO_INCREMENT , locking the table in this case will degrade performance and cause some unwanted effects.我认为最好使用AUTO_INCREMENT ,在这种情况下锁定表会降低性能并导致一些不良影响。 If you want the same format as str_pad, you can use laravel's Defining A Mutator如果你想要和 str_pad 一样的格式,可以使用 laravel 的Defining A Mutator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM