子查询

不相关子查询:

--子查询先执行,然后再执行外部查询。外部查询会使用到子查询的

--返回值。

 

--查询挣得的比亚伯多的雇员的姓名和薪水

select last_name,salary

  from employees

  where salary > (select salary

                   from employees

                   where last_name='Abel');

 

 

 

--子查询可以放在比较操作符的左边,但是这样写可读性很差

select last_name,salary

  from employees

  where (select salary

                   from employees

                   where last_name='Abel') < salary;

 

--单行子查询:

--子查询返回单行单列一个值

 

--多行子查询:

--子查询返回多行单列多个值

 

--对于单行子查询的返回值,在外部查询要使用单行比较操作符

--进行比较:=、>,<,<=,>=

 

--查找和Chen干同样的工作,但是挣得比Chen多的雇员的信息

select last_name,job_id,salary

  from employees

  where job_id = (select job_id

                   from employees

                   where last_name='Chen')

    and salary > (select salary

                   from employees

                   where last_name='Chen');

 

--子查询中也可以用组函数

--本例显示了月薪等于最低月薪的雇员的姓名、工作编号和月薪

select last_name,job_id,salary

  from employees

  where salary = (select min(salary)

                   from employees);

 

--注意,如果子查询返回的结果集为空,那么会把null值带入到

--外部查询中,这可能会导致外部查询的结果集也为空

select last_name,salary

  from employees

   where job_id = (select job_id

                    from employees

                    where last_name='Haas');

 

 

--对于多行子查询,在外部查询中要比较这些值,必须

--使用多行比较操作符:3个:in  any  all

--其中,any all不能单独用,在其前面必须加上单行比较操作符。

--例如:<any  >any=any <all >all等

 

 

--本例显示了工作不是IT程序员,

--并且工资少于任何一个程序员的雇员的信息

select last_name,salary

  from employees

  where salary <any (select salary

                   from employees

                   where job_id='IT_PROG')

  and job_id <> 'IT_PROG';

 

 

--本例显示了工作不是IT程序员,

--并且工资少于所有程序员的雇员的信息

select last_name,salary

  from employees

  where salary <all (select salary

                   from employees

                   where job_id='IT_PROG')

  and job_id <> 'IT_PROG';

 

--当外部查询的where条件使用not in 操作符时,要特别

--注意:如果子查询的返回值中有一个null值,会导致

--外部查询的where条件也为null,从而外查询的结果集为空

 

--查询所有普通雇员(没有当官的)的姓名

select last_name

  from employees

  where employee_id not in (selectmanager_id

                             from employees);

 

--解决办法:排除子查询结果集中的null值

select last_name

  from employees

  where employee_id not in (selectmanager_id

                             from employees

                             where manager_idis not null);

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值