我对这个标题感到抱歉。只是我不知道如何提出这个疑问,所以只是尝试实现我的目标。
我有两个表:玩家和团队。我的疑问是如何添加 5 名玩家,使用 一对多的关系,就像一支 5 名球员的球队,我尝试更新 团队中的玩家 ID,但它只返回最后一个玩家 ID。
create table if not exists player (
p_id int auto_increment not null,
p_name varchar(100) not null,
p_number int not null,
primary key (p_id)
);
create table if not exists team (
t_id int not null auto_increment,
t_name varchar(100) not null,
t_player_id int null,
primary key (t_id)
);
alter table team add constraint t_pk_player foreign key (t_player_id)
references player(p_id) on delete cascade;
存储过程
创建player
并返回id
DELIMITER $$
create procedure sp_create_player(in newName varchar(100),
in newNumber int,
out id_player int)
begin
insert into player (p_name, p_number) values (newName, newNumber);
-- get the id of player
set id_player := last_insert_id();
end$$
DELIMITER ;
存储过程
创建团队
并返回id
DELIMITER $$
create procedure sp_create_team(in newName varchar(100), out id_team int)
begin
insert into team (t_name) values (newName);
-- get the id of teams
set id_team := last_insert_id();
end$$
DELIMITER ;
我怀疑他在这个存储过程
中将添加玩家
到团队
DELIMITER $$
create procedure sp_add_player_in_team(in teamId int, in playerId int)
begin
-- I tried to make set but it´s not work
update team set t_player_id = playerId where t_id = teamId;
end$$
DELIMITER ;
测试存储过程
-- 5 player
call sp_create_player('De Gea', 1, @id_player1);
call sp_create_player('Rojo', 2, @id_player2);
call sp_create_player('Pogba', 3, @id_player3);
call sp_create_player('Rashford', 4, @id_player4);
call sp_create_player('Ibrahimovic', 5, @id_player5);
-- 1 team
call sp_create_team('Manchester United', @id_team);
-- select all player and team
SELECT * FROM player;
SELECT * FROM team;
-- add 5 player to team
call sp_add_player_in_team(@id_team, @id_player1);
call sp_add_player_in_team(@id_team, @id_player2);
call sp_add_player_in_team(@id_team, @id_player3);
call sp_add_player_in_team(@id_team, @id_player4);
call sp_add_player_in_team(@id_team, @id_player5);
-- select all player in team
SELECT t_player_id FROM team WHERE t_id = @id_team;
有什么建议吗?
最佳答案
您可能会倒退或过于简单地描述这种关系。如果玩家属于一个团队,并且只有一个团队,则玩家记录应引用团队记录。
如果玩家可以在多个团队中,那么你们将拥有多对多的关系;这需要一个额外的表,将玩家与他们所在的球队联系起来(从而将球队与他们所在的球员联系起来)。
您可能希望团队直接引用玩家的唯一情况是,如果您使用此类引用来指定团队“队长”或类似的内容,而团队中只有一个队长。如果您允许联合队长,或者想要指定一名球员在该团队中的角色,那么将其作为链接表上的一列可能会更好。
关于mysql - 插入值以更新mysql中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44532392/