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
1条答案
按热度按时间vddsk6oq1#
你可以在插入时触发。我已经为您的表创建了一个简化版本:
输出: