码迷,mamicode.com
首页 > 数据库 > 详细

mysql数据库的数据约束

时间:2018-11-20 13:19:34      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:table   let   into   res   外键   incr   销售   str   研发   

/*数据约束*/    
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数据库的数据约束

标签:table   let   into   res   外键   incr   销售   str   研发   

原文地址:https://www.cnblogs.com/zhaotao11/p/9988092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!