我正在尝试创建一个包含3列的表(Group_Name,Member,Position)。当我从数据库中的另一个表填充此表时,列Group_Name(政党)将包含重复项。当发生重复时,位置将增加1.例如:
Group_Name | Member | Position
------------------------------
democrats | joe b | 1
democrats | mark d | 2
democrats | owen l | 3
republican | esther d | 1
republican | tom d | 2
republican | ryan g | 3
republican | tea d | 4
pirate | bun r | 1
我使用Group_Name创建了表,而Position是主键。
CREATE TABLE Group_Membership ( Group_Name varchar(255) NOT NULL, Member varchar(255) NOT NULL, Position int, PRIMARY KEY (Group_Name, Position));
然后,当我插入数据时,每次复制时,位置应更新为1.
INSERT INTO Group_Membership(Group_Name, Member, Position) SELECT group_affiliation.value, group_affiliation.name, 1 FROM group_affiliation ON DUPLICATE KEY UPDATE Position = Position + 1;
但是我收到了一个错误:
Duplicate entry 'The Republican Party-2' for key 'PRIMARY'
我认为这是因为位置键不知道它之前的条目。
任何建议都会非常感激,因为这让我发疯!
答案 0 :(得分:0)
在插入之前检查触发器内的最大位置,如下所示:
DELIMITER $$
CREATE TRIGGER updatePosition BEFORE INSERT ON Group_Membership
FOR EACH ROW BEGIN
SET NEW.Position = (
SELECT IFNULL(MAX(Position), 0) + 1
FROM Group_Membership
WHERE Group_Name = NEW.Group_Name
);
END $$
DELIMITER ;