0
对于标题,我很抱歉。只是我不知道该如何表达这个疑问,所以试着实现我的目标。插入值更新mysql中的外键
我有两个表格:球员和球队。我的疑问是如何添加5名球员,使用 关系一对多的关系,就像一个球队为5名球员,我试图更新 队员的球员身份,但它只是返回最后一名球员身份。
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;
stored prodecure
创建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 ;
stored prodecure
创建team
并返回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 ;
和我到team
stored prodecure
到
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 ;
测试stored procedure
-- 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;
有什么建议?
你说我有三张桌子..但我看到只有两个被提及。这是一个错字吗? – Neels
它只是两张桌子,我的错误,但它已经编辑 –
您正在更新团队不插入新行。这样你只能得到最后一个玩家ID(来自上次调用的过程sp_add_player_in_team)。 尝试使用id_team,id_player列创建第三个表或将其插入到团队表中。 –