mysql02:连表
Posted lisa-blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql02:连表相关的知识,希望对你有一定的参考价值。
1,外键补充,一提到外键,肯定最少存在两张表的关系,外键有几个写几个就好
2,创建表的时候,最后一行不要加逗号,不然会报错的
mysql> create table userinfo( -> id int not null auto_increment primary key, -> name varchar(10), -> department_id int, -> ) engine=innodb default charset=utf8; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘) engine=innodb default charset=utf8‘ at line 5
3,两张表,创建简单的外键关系,这个报错的原因是因为department 表里面的id 不是唯一索引的,这个在后面会讲的我记忆当中
mysql> create table department( -> id int not null, -> department char(20) -> ) engine = innodb default charset utf8 -> ; Query OK, 0 rows affected, 1 warning (0.01 sec)
mysql> create table userinfo2( -> id int not null auto_increment primary key, -> name varchar(10), -> department_id int, -> constraint fk_1 foreign key (department_id) references department(id) -> ) engine=innodb default charset=utf8; ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint ‘fk_1‘ in the referenced table ‘department‘
4,所以应用上一小节学习的知识,修改department表里面的ID属性,正确写法如下,注意modify后面没有colume:
mysql> alter table department modify id int not null auto_increment primary key; Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0
5,修改完成之后,再次建立外键关系,成功!
mysql> create table userinfo2( id int not null auto_increment primary key, name varchar(10), department_id int, constraint fk_1 foreign key (department_id) references department(id) ) engine=innodb default charset=utf8; Query OK, 0 rows affected, 1 warning (0.01 sec)
6,做一下老师上节课的作业,创建出学生,老师,课程,成绩表,并建立约束关系
以上是关于mysql02:连表的主要内容,如果未能解决你的问题,请参考以下文章