SQL语句建表、设置主键、外键、check、default、unique约束

· 什么是数据库?html

  存放数据的仓库。sql

 

· 数据库和数据结构有什么区别?数据库

  数据结构要解决在内存中操做数据的问题,数据库要解决在硬盘中操做数据的问题。数据结构研究一些抽象数据模型(ADT)和以及定义在该模型上的一些操做,数据库是由表、关系、操做组成。数据结构

 

· 什么是主键?spa

  主键用来标识记录的惟一性。code

 

· 什么是外键?htm

  外键用来标识表与表之间的联系。blog

 

· 什么是check约束?教程

  check约束限制了输入值的范围。内存

 

· 什么是default约束?

  给某个属性一个默认值。

 

· 什么是unique约束?

  限制某个属性的惟一性。

 

· unique约束与主键有什么区别?

  主键不可为null。

 

关于以上知识的一些sql语句:

--部门表
create table dept ( dept_id int primary key, dept_name nvarchar(100) not null, dept_address nvarchar(100) ) --员工表
create table emp (--不能写成{
    emp_id int constraint pk_emp_id_hahaha primary key,--设置主键并命名
    emp_name nvarchar(20) not null,--名字不能为空
    emp_sex nchar(1), --↓设置外键,该外键来自于dept表(主键表)
    dept_id int constraint fk_dept_id_heihei foreign key references dept(dept_id), ) create table student ( stu_id int primary key, stu_sal int check (stu_sal >= 1000 and stu_sal <= 8000),--check约束
    stu_sex nchar(1) default ('') --()能够省略,在数据库中字符串必须用''括起来
) --向student表中插入数据
insert into student(stu_id,stu_sal) values (1,1000);--能够插入
insert into student(stu_id,stu_sal) values (2,10000);--插入失败,与check约束冲突
insert into student values (2,6000,'');--能够插入
insert into student values (3,6000);--错误,列的个数不匹配。

--再重建一个表
create table student2 ( stu_id int primary key, stu_sal int check (stu_sal >= 1000 and stu_sal <= 8000),--check约束
    stu_sex nchar(1) default (''), --()能够省略,在数据库中字符串必须用''括起来
    stu_name nvarchar(200) unique--qunique约束
) insert into student2 values (1,6000,'','张三');--ok
insert into student2 values (2,6000,'','张三');--error违反了惟一约束
insert into student2 values (3,6000,'','李四');--ok
insert into student2 values (null,6000,'','王五');--error主键不能为null,出错的信息是“不能将值 NULL 插入列 'stu_id'”
insert into student2 values (4,6000,'',null);--ok 说明 惟一键容许为空
insert into student2 values (5,6000,'',null);--error SqlServer2005只容许一个unique列为空

--再重建一个表
create table student3 ( stu_id int primary key, stu_sal int check (stu_sal >= 1000 and stu_sal <= 8000),--check约束
    stu_sex nchar(1) default (''), --()能够省略,在数据库中字符串必须用''括起来
    stu_name nvarchar(200) unique not null--qunique约束和not null约束能够组合使用
) insert into student3 values (3,6000,'',null);--error 证实了unique能够与not null组合使用

 

注:本文参考了郝斌老师的SQL教程,也加入了本身对SQL的一些理解,有写的不对的地方但愿你们可以指出来。