php - Mysql类似数据的int自增

标签 php mysql int auto-increment

所以这更多的是一个关于如何做到这一点的查询,当涉及到比基础知识更多的内容时,我是 MySQL/PHP 编码的新手,所以我只是想知道如何设置自动递增int 如果两个姓氏相同,则会将其计数。 我在网上搜索时找不到任何内容,但一个例子是:

数据库中有 5 个用户

 1. james smith 1   
 2. terry smith 2
 3. john smith 3
 4. jerry fields 1
 5. tom straus 1

当这些用户注册时,我需要创建一个 int,其中 john smith 是第三个具有相同姓氏 smith 的人,而 jerry fields 是第一个具有姓氏字段的人,等等。如何做到这一点?

我制作的表单是使用 jquery/php ajax 方法注册用户的表单,但是 我想添加与此类似的内容,以便将该数字与他们的姓名结合起来以生成特定的用户 ID。

最佳答案

Using AUTO_INCREMENT 下所述:

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(<em>auto_increment_column</em>) + 1 WHERE prefix=<em>given-prefix</em>. This is useful when you want to put data into ordered groups.

因此,你可以这样做:

CREATE TABLE my_table (
  firstname VARCHAR(31) NOT NULL,
  lastname  VARCHAR(31) NOT NULL,
  counter   BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (lastname, counter)
) Engine=MyISAM;

INSERT INTO my_table
  (firstname, lastname)
VALUES
  ('james', 'smith' ),
  ('terry', 'smith' ),
  ('john' , 'smith' ),
  ('jerry', 'fields'),
  ('tom'  , 'straus')
;

查看 sqlfiddle .

关于php - Mysql类似数据的int自增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319136/

相关文章:

php - 带有 sys_exec() 的 MySQL 过程

sql - mysql左连接升序

mysql - 字段 'user_data' 在 CI 2.0.3 中没有默认值

linux - 为什么 open(linux) 的返回值必须是 int 而不是 short?

c - 用户输入的数组元素之和的问题

php - 为什么 preg_match_all 返回两个匹配项?

php - 使用 SQL 筛选日期范围

mysql - 如何连接2个表,检查它们的每个元素是否存在于3个表中并将其表示为数字

python - 我收到类型错误 : '<' not supported between instances of 'str' and 'int'

JavaScript 隐藏/显示按钮