1. 程式人生 > >mysql資料庫的資料約束

mysql資料庫的資料約束

/*資料約束*/    
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);