您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

为mysql数据表添加外键(一)

2024/3/20 0:28:19发布29次查看
1. 什么是参照完整性? 参照完整性(完整性约束)是数据库设计中的一个重要概念,当数据库中的一个表与一个或多个表进行关联时都会涉及到参照完整性。比如下面这个例子: 文章分类表 - categories category_id name 1 sql server 2 oracle 3 postgresql 5 sqlit
1. 什么是参照完整性?
——————–
参照完整性(完整性约束)是数据库设计中的一个重要概念,当数据库中的一个表与一个或多个表进行关联时都会涉及到参照完整性。比如下面这个例子:
文章分类表 -   categories
category_id      name
1                sql server
2                oracle
3                postgresql
5                sqlite
文章表 - articles
article_id       category_id      title
1                1                aa
2                2                bb
3                4                cc
可见以上两个表之间是通过category_id,其中categories表有4条记录,articles表有3条记录。
然而可能因为某种原因我们删掉了categories 表中category_id=4的记录,而articles表却还是有一条category_id=4的记录,很明显,category_id=4的这条记录不应该存在在articles表中,这样会很容易造成数据错乱。
相反,外键关系(foreign key relationships)讨论的是父表(categories)与子表(articles)的关系,通过引入外键(foreign key)这个概念来保证参照完整性(referential integrity),将使会数据库变的非常简单。比如,要要做到删除categories表中category_id=4记录的同时删除 articles 表中category_id=4的所有记录,如果没有引入外键的话,我们就必须执行2条sql语句才行;如果有外键的话,可以很容易的用一条sql语句就可以达到要求。
2. 使用外键的条件
—————–
mysql只在v3.23.34版本以后才引入外键的,所以在这之前的版本就别想了:),除此之外,还必须具备以下几个条件:
     1) 在my.cnf配置文件中打开innodb引擎支持。
     # uncomment the following if you are using innodb tables
     innodb_data_home_dir = /var/db/mysql/
     innodb_data_file_path = ibdata1:10m:autoextend
     innodb_log_group_home_dir = /var/db/mysql/
     innodb_log_arch_dir = /var/db/mysql/
     2) 相关联的表都必须采用innodb引擎。
     3) 相关联的字段都必须建立所以。
     mysql v4.0版本以后,定义外键时会自动建立所以,所以在 v4.0 版本以前(含v4.0版本)必须手工定义索引。
     4) 相关联的字段必须采用类似的数据类型,或者说可转换的数据类型,当然相同类型是最好不过了。
     比如父表的字段是tinyint类型,则子表只能采用tinyint、smallint、int、bigint等几种类型。
3. 外键语法参考
—————
可以通过 create table 或者 alter table 来定义外键。
create table 语法:
create [temporary] table [if not exists] tbl_name
     [(create_definition,…)]
create_definition:
     column_definition
   | [constraint [symbol]] foreign key [index_name] (index_col_name,…) [reference_definition]
column_definition:
     col_name type [not null | null] [default default_value]
         [auto_increment] [unique [key] | [primary] key]
         [comment ’string’] [reference_definition]
index_col_name:
     col_name [(length)] [asc | desc]
reference_definition:
     references tbl_name [(index_col_name,…)]
                [match full | match partial | match simple]
                [on delete reference_option]
                [on update reference_option]
reference_option:
     restrict | cascade | set null | no action
alter table 语法:
alter [ignore] table tbl_name
     alter_specification [, alter_specification] …
alter_specification:
   | add [constraint [symbol]] primary key [index_type] (index_col_name,…)
   | add [constraint [symbol]] unique [index] [index_name] [index_type] (index_col_name,…)
   | add [constraint [symbol]] foreign key [index_name] (index_col_name,…) [reference_definition]
   | drop foreign key fk_symbol
4. 定义外键
———–
mysql> create table categories (
     -> category_id tinyint(3) unsigned not null auto_increment,
     -> name varchar(30) not null,
     -> primary key(category_id)
     -> ) engine=innodb;
query ok, 0 rows affected (0.36 sec)
mysql> insert into categories values (1, ‘sql server’), (2, ‘oracle’), (3, ‘postgresql’), (4, ‘mysql’), (5, ‘sqlite’);
query ok, 5 rows affected (0.48 sec)
records: 5   duplicates: 0   warnings: 0
mysql> create table members (
     -> member_id int(11) unsigned not null,
     -> name varchar(20) not null,
     -> primary key(member_id)
     -> ) engine=innodb;
query ok, 0 rows affected (0.55 sec)
mysql> insert into members values (1, ‘test’), (2, ‘admin’);
query ok, 2 rows affected (0.44 sec)
records: 2   duplicates: 0   warnings: 0
mysql> create table articles (
     -> article_id int(11) unsigned not null auto_increment,
     -> title varchar(255) not null,
     -> category_id tinyint(3) unsigned not null,
     -> member_id int(11) unsigned not null,
     -> index (category_id),
     -> foreign key (category_id) references categories (category_id),
     -> constraint fk_member foreign key (member_id) references members (member_id),
     -> primary key(article_id)
     -> ) engine=innodb;
query ok, 0 rows affected (0.63 sec)
注意:对于非innodb表,foreign key子句会被忽略掉。
如果遇到如下错误:
error 1005: can’t create table ‘./test/articles.frm’ (errno: 150)
请仔细检查以下定义语句,常见的错误一般都是表类型不是innodb、相关联的字段写错了、缺少索引等等。
至此categories.category_id和articles.category_id、members.member_id和 articles.member_id已经建立外键关系,只有 articles.category_id 的值存在与 categories.category_id 表中并且articles.member_id的值存在与members.member_id表中才会允许被插入或修改。例如:
mysql> insert into articles (category_id, member_id, title) values (6, 1, ‘foo’);
error 1452 (23000): cannot add or update a child row: a foreign key constraint fails (`test/articles`, constraint `articles_ibfk_1` foreign key (`category_id`)references `categories` (`id`))
mysql> insert into articles (category_id, member_id, title) values (3, 3, ‘foo’);
error 1452 (23000): cannot add or update a child row: a foreign key constraint fails (`test/articles`, constraint `fk_member` foreign key (`member_id`) references `members` (`member_id`))
可见上面两条语句都会出现错误,因为在categories表中并没有category_id=6、members表中也没有member_id=3的记录,所以不能插入。而下面这条sql语句就可以。
mysql> insert into articles (category_id, member_id, title) values (3, 2, ‘bar’);
query ok, 1 row affected (0.03 sec)
5. 删除外键定义
—————
不知道大家有没有发现,在前面定义外键的时候articles.member_id外键比articles.category_id子句多了一个constraint fk_member ?
这个fk_member就是用来删除外键定义用的,如下所示:
mysql> alter table articles drop foreign key fk_member;
query ok, 1 row affected (0.25 sec)
records: 1   duplicates: 0   warnings: 0
这样articles.member_id外键定义就被删除了,但是如果定义时没有指定constraint fk_symbol (即外键符号)时该怎么删除呢?别急,没有指定时,mysql会自己创建一个,可以通过以下命令查看:
mysql> show create table articles;
+———-+————————————+
| table     | create table                        |
+———-+————————————+
| articles | create table `articles` (
   `article_id` int(11) unsigned not null auto_increment,
   `category_id` tinyint(3) unsigned not null,
   `member_id` int(11) unsigned not null,
   `title` varchar(255) not null,
   primary key   (`article_id`),
   key `category_id` (`category_id`),
   key `member_id` (`member_id`),
   constraint `articles_ibfk_1` foreign key (`category_id`) references `categories` (`id`)
) engine=innodb default charset=latin1           |
+———-+————————————+
1 row in set (0.01 sec)
可以看出articles.category_id的外键符号为articles_ibfk_1,因为就可以执行以下命令删除外键定义:
mysql> alter table articles drop foreign key articles_ibfk_1;
query ok, 1 row affected (0.66 sec)
records: 1   duplicates: 0   warnings: 0
6. 总结
——-
引入外键的缺点是会使速度和性能下降,当然外键所带来的优点还有很多,本文仅讨论如何定义、删除外键。至于外键的实际应用将会在以后的文章中介绍。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product