主 键:数据库表中对储存数据对象予以唯一和完整标识的数据列或属性的组合。一个数据列只能有一个主键,且主键的取值不能缺失,即不能为空值(Null)。
超 键:在关系中能唯一标识元组的属性集称为关系模式的超键。一个属性可以为作为一个超键,多个属性组合在一起也可以作为一个超键。超键包含候选键和主键。候选键:是最小超键,即没有冗余元素的超键。外 键:在一个表中存在的另一个表的主键称此表的外键。主键一个数据列只能有一个主键,且主键的取值不能缺失,即不能为空值(Null)。单一主键(可以省略PRIMARY)CREATE TABLE IF NOT EXISTS user1( id INT PRIMARY KEY, username VARCHAR(20));复合主键CREATE TABLE IF NOT EXISTS user2( id INT, username VARCHAR(20), card CHAR(18), PRIMARY KEY(id,card));添加主键ALTER TABLE user12 ADD CONSTRAINT symbol PRIMARY KEY(id);ALTER TABLE user12 ADD PRIMARY KEY(id,card);删除主键ALTER TABLE user12 DROP PRIMARY KEY;CREATE TABLE IF NOT EXISTS test14(id INT UNSIGNED KEY AUTO_INCREMENT);自增长,主键,不能直接删除auto_increment ALTER TABLE TEST14 MODIFY id INT UNSIGNED;外键在一个表中存在的另一个表的主键称此表的外键。外键的作用是保持数据的一致性和完整性可以实现一对一或一对多的关系父表和子表必须使用相同的存储引擎(InnoDB)外键列必须和参照列具有相似的数据类型,必须都创建索引。创建部门表departmentid depName depDescCREATE TABLE IF NOT EXISTS department(id TINYINT UNSIGNED AUTO_INCREMENT KEY,depName VARCHAR(20) NOT NULL UNIQUE)ENGINE=INNODB;INSERT department(depName) VALUES('教学部'),('市场部'),('运营部'),('督导部');CREATE TABLE IF NOT EXISTS employee(id SMALLINT UNSIGNED AUTO_INCREMENT KEY,username VARCHAR(20) NOT NULL UNIQUE,depId TINYINT UNSIGNED,FOREIGN KEY(depId) REFERENCES department(id))ENGINE=INNODB;INSERT employee(username,depId)VALUES('KING',1),('KING1',2),('KING2',3),('KING3',4);SELECT e.id,e.username,d.depName FROM employee AS eJOINdepartment AS dON e.depId=d.id;delete from employee where depId=4;delete from department where depName='督导部';创建表时添加外键名称CREATE TABLE IF NOT EXISTS employee(id SMALLINT UNSIGNED AUTO_INCREMENT KEY,username VARCHAR(20) NOT NULL UNIQUE,depId TINYINT UNSIGNED,CONSTRAINT emp_fk_dep FOREIGN KEY(depId) REFERENCES department(id))ENGINE=INNODB;删除外键ALTER TABLE employee DROP FOREIGN KEY emp_fk_dep;添加外键ALTER TABLE employee ADD CONSTRAINT emp_fk_dep FOREIGN KEY(depId) REFERENCES department(id);父表和子表关联CREATE TABLE IF NOT EXISTS employee(id SMALLINT UNSIGNED AUTO_INCREMENT KEY,username VARCHAR(20) NOT NULL UNIQUE,depId TINYINT UNSIGNED,FOREIGN KEY(depId) REFERENCES department(id) ON DELETE CASCADE ON UPDATE CASCADE)ENGINE=INNODB;DELETE FROM department WHERE id=1;UPDATE department SET id=id+10;CREATE TABLE IF NOT EXISTS employee(id SMALLINT UNSIGNED AUTO_INCREMENT KEY,username VARCHAR(20) NOT NULL UNIQUE,depId TINYINT UNSIGNED,FOREIGN KEY(depId) REFERENCES department(id) ON DELETE SET NULL ON UPDATE SET NULL)ENGINE=INNODB;其他操作 NO ACTION RESTRICT