1.primary key
☆如果一个table有primary key,那么这个primary key 的value就不能为null,而且每条record就不能重复(完全相同),否则会发生如下错误
A.当primary key置为null时:ERROR 1048 (23000): Column 'id' cannot be null
B.当primary key 重复时:ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
例子:create table t2 ( id int(4) not null primary key, --auto_increment, name char(20) not null, sex int(4) not null default '0', degree double(16,2));
A.的sql语句:insert t2 values(1,'www',1,99.8);当执行两遍时报错
B.的sql语句:insert t2 values(null,'www',1,99.8);
结果:select * from t2;
+----+--------+------+----------+
| id | name | sex | degree |
+----+--------+------+----------+
| 1 | www | 1 | 99.80 |
+----+--------+------+----------+
否则,当table无primary key时
语句:create table t1 ( id int(4), name char(20));
C.insert t1 values (1,'www');可以执行n遍
D.insert t1 values (null,'www');也可以执行n遍
结果:select * from t1;
+--------+---------+
| id | name |
+--------+---------+
| 1 | www |
| 1 | www |
| NULL | www |
+--------+--------+
2.foreign key
外键的使用条件有三个
① 两个表必须是InnoDB表,MyISAM表暂时不支持外键
② 外键列必须建立了索引,MySQL 4.1.2以后的版本在建立外键时会自动创建索引,但如果在较早的版本则需要显式建立;
③ 外键关系的两个表的列必须是数据类型相似,也就是可以相互转换类型的列,比如int和tinyint可以,而int和char则不可以;
我们建立一个table:create table t1 ( id int(4), name char(20))type=innodb;并且建立索引create index t1_index on t1(name);
然后再建一个table:create table t3( id int(4),name char(20),foreign key(name) references t1(name)type=innodb );
那么 insert t3 values(1,'aaa');就会报错:ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`anwei`.`t3`, CONSTRAINT `t3_ibfk_1` FOREIGN KEY (`name`) REFERENCES `t1` (`name`))
但是在完成insert t1 values(1,'aaa');后就可以了,也就是values(1,'aaa');就不报错了,但是其他那么的值就又会报错的了。
说明:name是容许null值的,所以null值不受限制。
本文探讨了数据库中主键和外键的概念及其使用限制。主键确保记录唯一且非空,而外键用于维护不同表间的数据一致性,并强调了其在InnoDB表中的应用条件。
1182

被折叠的 条评论
为什么被折叠?



