composite (alphanumeric) primary key and auto increment

╄→尐↘猪︶ㄣ 提交于 2019-12-01 14:26:59

I asked this a while ago. Mysql doesn't do this unfortunately. I'd love it to, but it just doesn't. In php you could do it. Example:

public function random_id_gen($length)
    {
        //the characters you want in your id
        $characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
        $max = strlen($characters) - 1;
        $string = '';

        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[mt_rand(0, $max)];
        }

        return $string;
    } 

MySQL auto-increment are always numeric. There are a couple approaches you could take:

  • Implement your own incrementing in your app
  • Implement auto-increment with your alphanumeric key using a trigger
  • Use MySQL auto-increment, and then have your app convert the number to alphanumeric for display purposes.
  • As above, but use a view to have MySQL convert. (This would be one-way, as I don't believe MySQL supports instead-of triggers; see http://bugs.mysql.com/bug.php?id=16525)

As you probably realize, you can convert your sequence to a number and back; the 'a' through 'z' are just 0 through 250,000; if you go to double-a, that's 260,000. You've got base-26 system, multiplied by 10,000.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!