php/mysql自定义唯一引用

ia2d9nvy  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(351)

我正在建立一个应用程序,将允许不同的工作小组张贴在然而;我需要有一个独特的参考每个职位取决于哪个团队,他们是这样的逻辑是如下
团队1-所有职位都有一个id,比如[每个职位2、3等都会增加]

CMPLX001

第2组-所有职位将有一个id,如[将增加每个职位2,3等]

GNRLS001

我的问题是,当每个团队都需要从1开始,然后再递增时,如何递增每个
在数据库中插入新条目时,管理id的最佳方法是什么?

vddsk6oq

vddsk6oq1#

你可以在插入时触发。我已经为您的表创建了一个简化版本:

CREATE TABLE teams (id INT AUTO_INCREMENT PRIMARY KEY, 
                    name VARCHAR(20));

INSERT INTO teams (name) VALUES ('CMPLX'), ('GNRLS');

CREATE TABLE posts (id INT AUTO_INCREMENT PRIMARY KEY, 
                    team_id INT,
                    team_post_id INT,
                    notes VARCHAR(100));

ALTER TABLE posts ADD FOREIGN KEY (team_id) REFERENCES teams (id);

CREATE TRIGGER  update_tpid
BEFORE INSERT ON posts
FOR EACH ROW
  SET NEW.team_post_id = (SELECT IFNULL(MAX(team_post_id), 0) + 1
                          FROM posts 
                          WHERE team_id=NEW.team_id);

INSERT INTO posts (team_id, notes) VALUES
(1, 'team 1 first post'),
(2, 'team 2 first post'),
(1, 'team 1 second post'),
(1, 'team 1 third post'),
(2, 'team 2 second post'),
(1, 'team 1 fourth post'),
(2, 'team 2 third post'),
(1, 'team 1 fifth post');

SELECT concat(t.name, lpad(p.team_post_id, 3, '0')) AS post_id, p.notes 
FROM `posts` p
JOIN teams t ON t.id = p.team_id
ORDER BY p.id

输出:

post_id     notes   
CMPLX001    team 1 first post
GNRLS001    team 2 first post
CMPLX002    team 1 second post
CMPLX003    team 1 third post
GNRLS002    team 2 second post
CMPLX004    team 1 fourth post
GNRLS003    team 2 third post
CMPLX005    team 1 fifth post

相关问题