2017-06-13 137 views
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; 

有什么建议?

+0

你说我有三张桌子..但我看到只有两个被提及。这是一个错字吗? – Neels

+0

它只是两张桌子,我的错误,但它已经编辑 –

+0

您正在更新团队不插入新行。这样你只能得到最后一个玩家ID(来自上次调用的过程sp_add_player_in_team)。 尝试使用id_team,id_player列创建第三个表或将其插入到团队表中。 –

回答

1

你很可能代表这种关系,无论是向后还是过于简单。如果球员属于一支球队,只有一支球队,球员记录应该参考球队记录。

如果玩家可以在多个团队中,您将拥有多对多的关系;这需要一张额外的表格将球员与他们所在的球队相关联(并因此将球队与其上的球员相关联)。

您可能希望团队直接引用玩家的唯一场景是,如果您使用这样的参考来指定团队“队长”或类似团队中只有一个团队的情况。如果你允许联合队长,或者想要明确一个球员在该球队中的角色,那么它可能会更好地作为链接表上的一列。