MySQL 主外鍵約束與標準SQL不一樣的地方

標準SQL的外鍵約束條件sql

  1): 子表引用父表的主鍵學習

drop table if exists child,parent; create table if not exists parent( id int not null auto_increment primary key, v int ); create table if not exists child( id int not null auto_increment primary key, parent_id int not null, v int, constraint fk__child__parent_id foreign key (parent_id) references parent(id) ); insert into parent(id,v) values(1,100); insert into child(parent_id,v) values(1,1000); insert into child(parent_id,v) values(1,1000); select * from parent; +----+------+
| id | v    |
+----+------+
|  1 |  100 |
+----+------+

select * from child; +----+-----------+------+
| id | parent_id | v    |
+----+-----------+------+
|  1 |         1 | 1000 |
|  2 |         1 | 1000 |
+----+-----------+------+

 

  2): 子表引用交表的惟一索引ui

create table if not exists parent( id int not null, v int, constraint unique index uix__parent_id (id) ); create table if not exists child( id int not null auto_increment primary key, parent_id int not null, v int, constraint fk__child__parent_id foreign key (parent_id) references parent(id) ); insert into parent(id,v) values(1,100); insert into child(parent_id,v) values(1,1000); insert into child(parent_id,v) values(1,1000); select * from parent; +----+------+
| id | v    |
+----+------+
|  1 |  100 |
+----+------+


select * from child; +----+-----------+------+
| id | parent_id | v    |
+----+-----------+------+
|  1 |         1 | 1000 |
|  2 |         1 | 1000 |
+----+-----------+------+

 

innodb在標準SQL上作的擴展url

  1): 只要在父表上有在對應的列上建索引,那麼這個列就能在子表中引用spa

create table if not exists parent( id int not null auto_increment primary key, v int, index uix__parent_v (v) -- 只要父表上有索引就行
 ); create table if not exists child( id int not null auto_increment primary key, parent_v int not null, v int, constraint fk__child__parent_v foreign key (parent_v) references parent(v) -- 在子表中引用 
 ); insert into parent(id,v) values(1,100); insert into parent(id,v) values(2,100); insert into child(parent_v,v) values(100,2000); insert into child(parent_v,v) values(100,2000); select * from parent; +----+------+
| id | v    |
+----+------+
|  1 |  100 |
|  2 |  100 |
+----+------+

select * from child; +----+----------+------+
| id | parent_v | v    |
+----+----------+------+
|  1 |      100 | 2000 |
|  2 |      100 | 2000 |
+----+----------+------+

 

 

個人評介.net

  主外鍵約束在標準SQL下體現的是一種一對多的關係,可是通過MySQL的拓展以後能夠表現出「多對多」的關係;雖然MySQL這樣設計

  的設計有必定的靈活性,我的以爲最好仍是使用標準SQL的方式。code

 

學習交流blog

 

 -----------------------------http://www.sqlpy.com-------------------------------------------------索引

 -----------------------------http://www.sqlpy.com-------------------------------------------------

相關文章
相關標籤/搜索