我很抱歉这个头衔。只是我不知道如何解释这个问题,所以试着实现我的目标。
我有两张桌子:球员和球队。我怀疑是如何添加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;
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 ;
我怀疑他在stored prodecure
到add player
到team
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;
有什么建议吗?
答案 0 :(得分:1)
您可能会向后或过于简单地表达这种关系。如果玩家属于一个团队,并且只有一个团队,则玩家记录应该参考团队记录。
如果玩家可以在多个团队中,那么你将拥有多对多的关系;这需要一个额外的表格,将球员与他们所在的球队联系起来(并因此与球队的队员联系)。
您可能希望团队直接引用玩家的唯一情况是,如果您使用此类引用来指定团队"队长"或类似的东西,只有一个团队。如果您允许联合队长,或者想要在该团队中确定玩家的角色,那么它可能会更好地作为链接表上的列。