SQL主外键和子查询

主键

数据库主键是指表中一个列或列的组合,其值能唯一地标识表中的每一行。这样的一列或多列称为表的主键,通过它可强制表的实体完整性。当创建或更改表时可通过定义 PRIMARY KEY约束来创建主键。一个表只能有一个 PRIMARY KEY 约束,而且 PRIMARY KEY 约束中的列不能接受空值。由于 PRIMARY KEY 约束确保唯一数据,所以经常用来定义标识列。

主键的作用

主键的主要作用如下:

(1)保证实体的完整性;

(2)加快数据库的操作速度;

(3) 在表中添加新记录时,数据库会自动检查新记录的主键值,不允许该值与其他记录的主键值重复;

(4) 数据库自动按主键值的顺序显示表中的记录。如果没有定义主键,则按输入记录的顺序显示表中的记录。

 

主键具有的特点:唯一性、非空性。

 

设置主键语句示例:

code int primary key,   主键不能为空,不能重复,确保唯一性

设置自增长主键语句示例:

code int primary key identity(1,1)从1开始,每次增长1,添加values时不用添加此列

 

 

设置外键:

      在要设置外键的表上右键,选择设计,在需要设置外键的列名前右键,如下图:

选择关系单击,出现对话框,单击添加,单击表和列规范后面的省略号,如下图:

 

在出现的界面做出如下操作:

 

点击确定,再点击确定,操作成功。

 

子查询,又叫做嵌套查询。

 

         将一个查询语句做为一个结果集供其他SQL语句使用,就像使用普通的表一样,被当作结果集的查询语句被称为子查询。

 

子查询有两种类型:

 

一种是只返回一个单值的子查询,这时它可以用在一个单值可以使用的地方,这时子查询可以看作是一个拥有返回值的函数;

 

另外一种是返回一列值的子查询,这时子查询可以看作是一个在内存中临时存在的数据表。

 

 

新建一个部门表,一个员工表,员工表中每个人员的部门列用部门的编号。

 

子查询示例:

 

 

练习:

建立两个表:

1.选课ID 科目名称 老师姓名 老师年龄

2.学号  姓名  选课ID

我就要选  A老师  教的课

我就要选  老师年龄最小的 课

某个学生选的  哪门课  哪个老师  多少岁

有几个人选了  老师A   都叫什么

用代码  给  学生表加一个年龄列

我就要比我小的老师教

老师A的学生里 年龄最小的

所有选择  数学的学生 信息

所有学生选择的老师年龄大于20的  学生信息
create table student
(
    scode int primary key identity(1001,1),
    sname varchar(10),
    xuanke int
)
create table teacher
(
    tcode int primary key identity(1,1),
    kemu varchar(18),
    tname varchar(10),
    age int
)
insert into teacher values('数学','张三',31)
insert into teacher values('语文','李四',36)
insert into teacher values('英语','王五',28)
insert into teacher values('物理','赵六',50)
insert into teacher values('化学','冯七',24)
insert into student values('AA',1)
insert into student values('BB',2)
insert into student values('CC',3)
insert into student values('DD',4)
insert into student values('EE',5)
insert into student values('FF',5)
select * from student
select * from teacher
select kemu from teacher where tname='张三'
select top 1 kemu from teacher order by age
select kemu,tname,age from teacher where tcode=(select xuanke from student where scode=1002)
select sname from student where xuanke=(select tcode from teacher where tname='张三')
alter table student
add sage int
select top 1 sname from student where xuanke=(select tcode from teacher where tname='张三') order by sage
select * from teacher where age<(select sage from student where scode=1003)
select * from student where xuanke in (select tcode from teacher where kemu='数学')
select * from student where xuanke in (select tcode from teacher where age>20)

 

原文地址:https://www.cnblogs.com/wt627939556/p/6074177.html