数据库,表的创建、主键,外键,check约束

一,需要先建立数据库

看这一篇文章,请点击

二,表的创建

例如:
图书(书号,书名,价格,出版社)
读者(卡号,姓名,年龄,所属单位)
借阅(书号,卡号,借阅日期)

1,先给出具体的例子

--建立表

use shu
create table tushu   --创建表
    (
    	--创建列开始
    	shuid int constraint pk_shuid primary key, --编号 类型int 主键
    	shuname nvarchar(max) not null,   --shuname 书名 类型nvarchar(max) 非空
    	price money,    -- 类型
    	chubanshe nvarchar(max) --
)

use shu
create table duzhe
(
	kid int constraint pk_kid primary key,
	dname nvarchar(max),
	age int check(age>10 and age<100),
	suoshudanwei nvarchar(max)
)

use shu
create table jieyue
(
	shuid int constraint fk_tushu_jieyue foreign key references tushu(shuid),
	kid int constraint fk_duzhe_jieyue foreign key references duzhe(kid),
	jieyueriqi date
)
--alter table duzhe
--add constraint ck_age check(age >0 and age <100)
use shu
alter table tushu
add constraint ck_price check(price >0 and price <1000)

2,总结

创建表的语句:
use 数据库的名称
create table 表名称
(
列名1 数据类型1 约束1,
列名2 数据类型2 约束2,
列名3 数据类型3 约束3
)

3,数据类型

主要有
int
float
nvarchar(MAX)
nvarchar(50)
money
date

4,设置主外键

1.设置主键
属性名称 数据类型 constraint 主键的名称 primary key

shuid int constraint pk_shuid primary key, --书编号 类型int 主键
kid int constraint pk_kid primary key,
2.设置外键
属性名1 数据类型1 constraint 外键名称 foreign key references 表2(属性名2),

shuid int constraint fk_tushu_jieyue foreign key references tushu(shuid),
kid int constraint fk_duzhe_jieyue foreign key references duzhe(kid),

5,check约束

这里介绍2种方法

1,在创建表时设置

总结
属性名 数据类型 (属性名的范围)

age int check(age>10 and age<100),

2,在表外设置

总结
use 数据库名称
altertable 表名称
add constraint 约束名称 check(范围)

use shu
alter table tushu
add constraint ck_price check(price >0 and price <1000)

三,表的查询

见这一篇文章

若有不足,欢迎大家评论,补充

1级标题后面的文章点这里

  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值