「Mysql/外部キー」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==外部キー設定== // 親テーブル drop table if exists users; create table users(id int not null primary key auto_increment, name varchar(10)) engine=innodb;...」) |
(→外部キー設定) |
||
| 行2: | 行2: | ||
// 親テーブル | // 親テーブル | ||
drop table if exists users; | drop table if exists users; | ||
| − | create table users(id int not null primary key auto_increment, name varchar(10)) engine=innodb; | + | create table users( |
| + | id int not null primary key auto_increment, | ||
| + | name varchar(10) | ||
| + | ) engine=innodb; | ||
| + | |||
// 子テーブル | // 子テーブル | ||
drop table if exists contents; | drop table if exists contents; | ||
| − | create table contents(id int not null primary key auto_increment, user_id int, foreign key(user_id) references users(id)) engine=innodb; | + | create table contents( |
| + | id int not null primary key auto_increment, | ||
| + | user_id int, | ||
| + | foreign key(user_id) references users(id) | ||
| + | ) engine=innodb; | ||
insert into users(name) values('test1'); | insert into users(name) values('test1'); | ||
2016年8月15日 (月) 15:29時点における版
外部キー設定
// 親テーブル drop table if exists users; create table users( id int not null primary key auto_increment, name varchar(10) ) engine=innodb;
// 子テーブル
drop table if exists contents;
create table contents(
id int not null primary key auto_increment,
user_id int,
foreign key(user_id) references users(id)
) engine=innodb;
insert into users(name) values('test1');
insert into contents(user_id) values(1); // 成功
insert into contents(user_id) values(4); // 失敗
