所以这更多的是一个关于如何做到这一点的查询,当涉及到比基础知识更多的内容时,我是 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
andBDB
tables you can specifyAUTO_INCREMENT
on a secondary column in a multiple-column index. In this case, the generated value for theAUTO_INCREMENT
column is calculated asMAX(<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/