约束、级联
CREATE TABLE sto(
id INT,
NAME VARCHAR(20) NOT NULL
);
ALTER TABLE sto MODIFY NAME VARCHAR(20);
ALTER TABLE sto MODIFY NAME VARCHAR(20) NOT NULL;
SELECT * FROM sto;
CREATE TABLE sto(
id INT,
tel VARCHAR(20) UNIQUE
);
ALTER TABLE sto DROP INDEX tel;
ALTER TABLE sto MODIFY tel VARCHAR(20) UNIQUE;
CREATE TABLE sto(
id INT PRIMARY KEY,
tel VARCHAR(20) UNIQUE
);
ALTER TABLE sto DROP PRIMARY KEY;
ALTER TABLE sto MODIFY id INT PRIMARY KEY;
CREATE TABLE sto(
id INT PRIMARY KEY AUTO_INCREMENT,
tel VARCHAR(20) UNIQUE
);
ALTER TABLE sto MODIFY id INT;
ALTER TABLE sto MODIFY id INT AUTO_INCREMENT;
CREATE TABLE emp (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(30),
age INT,
dep_name VARCHAR(30),
dep_location VARCHAR(30)
);
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('张三', 20, '研发部', '广州');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('李四', 21, '研发部', '广州');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('王五', 20, '研发部', '广州');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('老王', 20, '销售部', '深圳');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('大王', 22, '销售部', '深圳');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('小王', 18, '销售部', '深圳');
select * from emp;
create table department(
id int primary key auto_increment,
dep_name varchar(20),
dep_location varchar(20)
);
create table employee(
id int primary key auto_increment,
name varchar(20),
age int,
dep_id int,
constraint emp_dep_id foreign key (dep_id) references department(id)
);
insert into department values(null, '研发部','广州'),(null, '销售部', '深圳');
select * from department;
INSERT INTO employee (NAME, age, dep_id) VALUES ('张三', 20, 1);
INSERT INTO employee (NAME, age, dep_id) VALUES ('李四', 21, 1);
INSERT INTO employee (NAME, age, dep_id) VALUES ('王五', 20, 1);
INSERT INTO employee (NAME, age, dep_id) VALUES ('老王', 20, 2);
INSERT INTO employee (NAME, age, dep_id) VALUES ('大王', 22, 2);
INSERT INTO employee (NAME, age, dep_id) VALUES ('小王', 18, 2);
select * from employee;
drop table emp;
drop table department;
drop table employee;
alter table employee add constraint emp_dep_id foreign key (dep_id) references department(id);
alter table employee drop foreign key emp_dep_id;
添加级联
UPDATE employee SET dep_id = NULL WHERE dep_id = 1;
SELECT * FROM employee;
UPDATE department SET id = 5 WHERE id = 1;
SELECT * FROM department;
UPDATE employee SET dep_id = 5 WHERE dep_id IS NULL;
ALTER TABLE employee ADD CONSTRAINT emp_dep_fk FOREIGN KEY (dep_id) REFERENCES department(id) ON UPDATE CASCADE;
UPDATE department SET id = 1 WHERE id = 5;
ALTER TABLE employee ADD CONSTRAINT emp_dep_fk FOREIGN KEY (dep_id) REFERENCES department(id) ON UPDATE CASCADE ON DELETE CASCADE;