1. 程式人生 > >mysql數據庫的數據約束

mysql數據庫的數據約束

update prim mar rom sql數據庫 from incr null 紅帽

/*數據約束*/
CREATE TABLE user01 (
uid INT NOT NULL,/*非空約束*/ PRIMARY KEY /*主鍵約束*/ AUTO_INCREMENT /*自增長*/
uname VARCHAR(10) UNIQUE,/*唯一約束*/
address VARCHAR(20) DEFAULT‘張店‘/*默認值約束*/
);
INSERT INTO user01 VALUES(1,‘小紅帽‘,‘博山‘);
INSERT INTO user01(uname) VALUES(‘大灰狼‘);
SELECT * FROM user01;
DROP TABLE user01;

/*外鍵約束*/
CREATE TABLE emp1( /*副表*/
eid INT PRIMARY KEY AUTO_INCREMENT,
ename VARCHAR(10),
deptid INT,
CONSTRAINT emp1_dept_fk FOREIGN KEY(deptid) REFERENCES dept(id)/*添加外鍵約束*/
);
INSERT INTO emp1(ename,deptid) VALUES(‘張三‘,5);
INSERT INTO emp1(ename,deptid) VALUES(‘李四‘,4);
INSERT INTO emp1(ename,deptid) VALUES(‘王五‘,3);
INSERT INTO emp1(ename,deptid) VALUES(‘張五‘,2);
SELECT * FROM emp1;
DROP TABLE emp1;
CREATE TABLE dept( /*主表*/
id INT PRIMARY KEY AUTO_INCREMENT,
dname VARCHAR(15)
);
INSERT INTO dept(dname) VALUES(‘研發部‘);
INSERT INTO dept(dname) VALUES(‘產品部‘);
INSERT INTO dept(dname) VALUES(‘銷售部‘);
SELECT * FROM dept;
DROP TABLE dept;
/*修改數據(先改副表再改主表)*/
UPDATE emp SET deptid=1 WHERE eid=2;
UPDATE dept SET id=5 WHERE id=2;
/*刪除數據(先刪副表再刪主表)*/
DELETE FROM emp WHERE eid=1;
DELETE FROM dept WHERE id=3;

/*兩種全表刪除的區別*/
CREATE TABLE test(
id INT PRIMARY KEY AUTO_INCREMENT,
tname VARCHAR(10)
);
INSERT INTO test(tname) VALUES(‘小紅‘);
INSERT INTO test(tname) VALUES(‘小藍‘);
INSERT INTO test(tname) VALUES(‘小綠‘);
SELECT * FROM test;
DELETE FROM test; /*不會刪除約束*/
TRUNCATE TABLE test;/*會刪除約束*/
DROP TABLE test;
/*先建表後添加外鍵約束*/
CREATE TABLE test(
id INT PRIMARY KEY AUTO_INCREMENT,
tname VARCHAR(10),
empid INT
);
ALTER TABLE test
ADD CONSTRAINT test_emp1_fk FOREIGN KEY(empid)
REFERENCES emp1(eid);

mysql數據庫的數據約束