gpt4 book ai didi

mysql - 如何实现每组用户的序号数据库?

转载 作者:行者123 更新时间:2023-11-29 01:44:10 25 4
gpt4 key购买 nike

创建用于存储序列 数字的数据库表很容易;但这种设计适用于 sequence 为所有用户共享的事件。我想要的是为每个 group 用户创建 sequence :这个 group 可以随时增长,因为它是一个数据库表,就是管理员可以随时创建一个组,并将用户分配到一个特定的组。那么如何实现按组生成sequence呢?

最佳答案

如果你使用的是myisam

http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

下面是从上面的链接中提取的。

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

CREATE TABLE animals (
grp ENUM('fish','mammal','bird') NOT NULL,
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (grp,id)
) ENGINE=MyISAM;

INSERT INTO animals (grp,name) VALUES
('mammal','dog'),('mammal','cat'),
('bird','penguin'),('fish','lax'),('mammal','whale'),
('bird','ostrich');

SELECT * FROM animals ORDER BY grp,id;
Which returns:

+--------+----+---------+
| grp | id | name |
+--------+----+---------+
| fish | 1 | lax |
| mammal | 1 | dog |
| mammal | 2 | cat |
| mammal | 3 | whale |
| bird | 1 | penguin |
| bird | 2 | ostrich |
+--------+----+---------+

针对您的情况:

CREATE TABLE mytable (
user_id MEDIUMINT NOT NULL AUTO_INCREMENT,
group_id MEDIUMINT NOT NULL,
user_name CHAR(30) NOT NULL,
PRIMARY KEY (group_id,user_id)
) ENGINE=MyISAM;


INSERT INTO mytable (group_id, user_name) VALUES
(1,'alex'),(1,'jenny'),(2,'baz'),(1,'tim'),(2,'danny'),(3,'joe');


SELECT * FROM mytable ORDER BY group_id,user_id;

返回:

user_id group_id    user_name
1 1 alex
2 1 jenny
3 1 tim
1 2 baz
2 2 danny
1 3 joe

关于mysql - 如何实现每组用户的序号数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11466539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com