简单的SQL语句学习资料 经典SQL语句(下)

本文介绍了SQL中的高级查询技巧,包括嵌套查询、使用IN与EXISTS关键字、排序方法、处理空值及复杂嵌套查询等。通过这些技巧,可以帮助开发者更高效地进行数据检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相当于做笛卡儿积 

8.嵌套查询

  a.用关键字IN,如查询李山的同乡:

  select * from students

  where native in (select native from students where name=’ 李山’)

  b.使用关键字EXIST,比如,下面两句是等价的:

  select * from students

  where sno in (select sno from grades where cno=’B2’)

  select * from students where exists

  (select * from grades where

  grades.sno=students.sno AND cno=’B2’)

  9.关于排序order

  a.对于排序order,有两种方法:asc升序和desc降序

  b.对于排序order,可以按照查询条件中的某项排列,而且这项可用数字表示,如:

  select sno,count(*) ,avg(mark) from grades

  group by sno

  having avg(mark)>85

  order by 3

  10.其他

  a.对于有空格的识别名称,应该用"[]"括住。

  b.对于某列中没有数据的特定查询可以用null判断,如select sno,courseno from grades where mark IS NULL

  c.注意区分在嵌套查询中使用的any与all的区别,any相当于逻辑运算“||”而all则相当于逻辑运算“&&”

  d.注意在做否定意义的查询是小心进入陷阱:

  如,没有选修‘B2’课程的学生 :

  select students.*

  from students, grades

  where students.sno=grades.sno

  AND grades.cno <> ’B2’

  上面的查询方式是错误的,正确方式见下方:

  select * from students

  where not exists (select * from grades

  where grades.sno=students.sno AND cno='B2')

  11.关于有难度多重嵌套查询的解决思想:

  如,选修了全部课程的学生:

  select *

  from students

  where not exists ( select *

  from courses 

  where NOT EXISTS

  (select *

  from grades

  where sno=students.sno

  AND cno=courses.cno))

http://news.newhua.com/html/Deve_data/2007-3/9/073910391283149_62_2.shtml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值