数据库高级查询语句

嵌套子查询:

    子查询的优势和特点


        使用灵活,可以成为sql语句的多个部分

        ·子查询作为查询条件使用

        ·子查询作为临时表使用

        降低sql语句的复杂度,提高sql语句的可读性

作为临时表使用
    
    例:select stuname ,subject,score from
    (select * from stuinfo where name='李四') s1,
    (select * from stumarks where score > 80) s2,
    where s1.stuid=s2.stuid
    
作为查询条件使用

    例:select * from stuinfo where stuid <
    (select stuid from stuinfo where stuname = '王五')

作为列使用
    
    例:select s.*,(select score stumarks where subject = 'html'
    and s.stuid=stumarks.stuid) as '成绩' from stuinfo s

使用in和not in完成子查询

    in和not in 通常在where子句中使用,在in和not in
    后接的子查询可以多个值出现大半年必须只能有一列

例:select * from stuinfo where stuid in (1,3)

    not in和in的用法一样只是意思相反

使用exists 和 not exists子查询

    ·exists 和 not exists表示存在和不存在的意思
    
    ·在语句中会判断exists 和 not exists后接的子句是否存在和是否不存在

    ·exists 和 not exists用法一样,只是意思相反

例:select * from stuinfo where exists
(select * from stumarks where stumarks.stuid=stuinfo.stuid)

使用some、any、all进行子查询

    在sql查询中some、any、all后必须跟子查询

    在sql查询中,some和any的作用是一样的,表示其中的任何一项
    all则表示其中的所有的项

使用compute和compute by 进行汇总查询

compute 进行汇总计算后查询得到两个结果集,第一个是返回查询语句前面的查询明细
后一个结果集返回汇总结果

需要对结果先进行分组然后进行汇总计算的时候可以使用compute by进行分组汇总查询

排序函数

    语法:排序函数 over([分组子句] 排序子句 [desc/asc])

row_number 函数生成的排序根据排序子句给出递增连续的序号

rank 函数生成的排序根据排序子句给出递增的序号,但是存在并列并且跳空

dense_rank函数生成的排序根据排序子句给出递增连续的序号,但是存在并列不跳空

分组子句:partition by 分组列,分组列...

排序子句:order by 排序列,排序列...


例:select dense_rank() over(partition by subject order by score desc),
 stuinfo.stuid,stuname,sbject from stuinfo,stumarks where
 stuinfo.stuid=stumarks.stuid


公式表达式:

with g_name(stuid,stuname,score)
as
(
    select s1.stuid,s1.stuname,s2.score
    from stuinfo s1,stumarks s2
    where s1.stuid=s2.stuid and subject='sql'
)
select * from g_name
go

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值