您的位置:首页 > 数据库

SQL Server 基础 05 多链表查询和子查询

2014-05-08 00:03 169 查看
连接查询

值得注意的是:字段前必须加表名,以便混淆

-- 多表连接查询和子查询
select * from dbo.stu_info ,dbo.sname2
-- 加连接规则的查询 where
select * from dbo.stu_info ,dbo.sname2 where dbo.stu_info.sname= dbo.sname2.姓名


使用where前



使用where后



使用逻辑运算符 and

select dbo.stu_info.sno,dbo.stu_info.sname,dbo.stu_info.sex,dbo.stu_info.depart
,dbo.sname2.score,dbo.sname2.姓名,dbo.sname2.sno
from dbo.stu_info,dbo.sname2
where dbo.stu_info.sname='张三'
and dbo.stu_info.sno=dbo.sname2.sno
order by dbo.sname2.score desc


表别名简化语句

select A.sno,A.sname,A.sex,A.depart
,B.score,B.姓名,B.sno
from dbo.stu_info as A,dbo.sname2 as B
where A.sname='张三'
and A.sno=B.sno
order by B.score desc


多表连接查询

跟上面的相似,只是 from 后面多了n个表名 同时多了n-1 个 and 。。。

使用 inner join 连接查询

在where子句中表达式变的臃肿,为了变得清晰,让人理解,所以 ansi SQL 建议使用 inner join 进行多表连接

语法格式 :

select * from 表名1

inner join 表名2

on 连接规则1

inner join 表名3

on 连接规则2

. . . . . .

inner join 表名n

on 连接规则n-1

举例 :

-- 使用 inner join
select * from dbo.stu_info as A
inner join dbo.sname2 as B
on A.sno=B.sno
where A.depart='心理学'
order by B.score desc




/**/ 相比上面的 where + and 更简单

高级连接查询

// 这里只是粗略的概括下,来自 书本:《21 天学通SQL Server》 第11章 P226

1、自动连接查询

/**/

select 表名1.* from 表名1,表名2 where 表名1.字段=表名2.字段 and 表名2.字段=‘字段值’

2、内连接查询

等值连接 : 表名1.*=表名2.*

自然连接 : select 后面不使用* ,而是字段名

不等值连接 : 由 >、>=、< 、<= 、<> 、between . . . 查询某些范围内的值

3、左外连接查询

语法 :select * from 表名1 left outer join 表名2 on 表名1.字段=表名2.字段

4、右外连接查询

语法 :select * from 表名1 right outer join 表名2 on 表名1.字段=表名2.字段

5、全外连接查询

语法 :select * from 表名1 full outer join 表名2 on 表名1.字段=表名2.字段

6、交叉连接查询

语法 :select * from 表名1 cross join 表名2

组合查询

-- 使用组合查询union

select * from dbo.stu_info where depart='心理学'
union
select * from dbo.stu_info where datediff(year,date,getdate())>30

-- union 、group by 、聚合函数 三者共同使用
select sno,姓名,score from dbo.sname2
union
select '总分:',姓名,sum(score) from dbo.sname2 group by 姓名
union
select '平均分:',姓名,avg(score) from dbo.sname2 group by 姓名


子查询

select语句中中镶陶一个select语句

语法 :

select 字段1 ,字段2 from 表

where 字段2=(select 字段2 from 表2 where 字段3=‘字段值’)

order by 字段4 desc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: