タイトルには申し訳ありません。私はこの疑念をどうやって入れていいのか分からないので、私の目標を実現しようとしています。mysqlの外部キーを更新するための値を挿入します。
私は2つのテーブル:プレーヤーとチームを持っています。私の疑問は、5人のプレーヤーを追加する方法です。 の関係を1対多の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
を作成し、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
add player
この
stored prodecure
で私の疑問に彼を返すために
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
戻ります
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;
任意の提案をテストしますか?
私は3つのテーブルを持っていると言っていますが、2つしか言及されていません。それはタイプミスですか? – Neels
それはちょうど2つのテーブル、私の間違いですが、それはすでに編集しています –
あなたは新しい行を挿入しないチームを更新しています。この方法で最後のプレイヤーID(最後に呼び出された手続きsp_add_player_in_teamから)だけを取得します。 id_team、id_playerカラムを使用して3番目のテーブルを作成するか、チームテーブルに挿入してください。 –