复杂sql

本文详细介绍了使用SQL进行复杂查询的方法,包括子查询、外连接、自我连接等高级技巧,并展示了如何通过UNION、INTERSECT及MINUS操作符来处理多表数据,帮助读者掌握高效的数据检索技能。

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

1.我有一个table:COMPUTER_PRICE,格式如下:

goods       price          dates
HP电脑       20000          5.21
HP电脑       20050          5.23
NEC电脑      31200          5.3
NEC电脑      32000          5.5

查询结果要求:要查出每种电脑的最新价格;
上面表的结果为:
goods       price           dates
HP电脑       20050          5.23

NEC电脑      32000          5.5

select goods,price,dates from COMPUTER_PRICE where dates=(select max(dates) from computer_price group by goods);
select goods,price,dates from computer_price where dates in(select max(dates) from computer_price group by goods)
select goods,price,dates from computer_price where (goods,dates)=(select goods,max(dates) from computer_price group by goods)
1.1相关子查询
  
  可以将子查询(as subquery)或in或exists当成where的一个条件的一部分,这样的查询称为子查询
  
  .where中可以包含一个select语句的子查询
  

  .where中可以包含in,exists语句

1.2外连接

select a.* , b.skill from students a,student_skill b where a.st_id=b.st_id  
 order by a.st_id;  

1.3自我连接

select e1.ename ||'  work for  '|| e2.ename "Employees and their Managers"  
   
 from scott.emp e1,scott.emp e2 where e1.mgr=e2.empno;  
1.4UNION , INTERSECT及 MINUS
  
  UNION:      可以将两个以上的表的相类似的查询结果放在一起 (union all则表示返回所有的行)
  
  具体语法:
  
  select ...
  union[all]
  select...
  ==========
  
  INTERSECT: 返回两个表中相同的信息
  具体语法:
  select ...
  intersect
  select...
  ==========
  
  MINUS     : 返回一个表中出现的信息
  具体语法:
  select ...
  minus
  select...
select st_id from students  
   union  
   select st_id from student_skill; 

列出有特长的学生的学号

select st_id from students  
    intersect  
   select st_id from student_skill;  

列出没有特长学生的学号

select st_id from students  
  minus  
  select st_id from student_skill; 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值