首页 > 代码库 > 2017-3-13 SQL server 表连接

2017-3-13 SQL server 表连接

表连接分为横向表连接和纵向表连接

横向表连接有三种方式:

1、select 列名,列名 from 表名,表名 where 表名.列名=表名.列名

select student.Sno,sname,cno,degree from Student,Score
where Student.Sno = Score.Sno

2、子查询方式

select sno,sname,(select cno from Score where Student.Sno=Score.Sno) from Student

3、select 列名,列名 from 表名 join 表名 on 表名.列名=表名.列名

select Student.Sno,sname,Score.Cno,DEGREE,cname
from Student join Score on Student.Sno=Score.Sno
join Course on Score.Cno = Course.cno

 纵向表连接:(注:两个表必须是同样的列数,对应的列数据类型必须一致)

select  列名,列名 from 表名 union select  列名,列名 from 表名

select sno 编号,sname 姓名,ssex 性别,sbirthday 生日 from Student
union
select tno,tname,tsex,tbirthday from Teacher

--------------------------------------------------------------------------------------------------------------------------------------------

灵活用法

select Student.sno,sname+‘同学‘,cname,abs(degree+10)
from Student,Score,Course
where Student.Sno=Score.Sno and Score.Cno=Course.Cno
and student.Sno=‘107‘

 

2017-3-13 SQL server 表连接