SQL 查询(进阶)

SQL 查询(进阶)

单表查询

-- 1.查询有直接先行课的课程的课号,课名和先行课号。
select 课程号,课程名,先行课号
from kc
where 先行课号 is not null

where 语句用于对查询前的筛选条件,本例中通过where语句,查询结果只有先行课号非空的元组。

嵌套查询

嵌套查询思路很直接: 一步步求,碰见直接无法得到的数据,就递归地一层层求解出来。缺点是查询数据过多时,多表联合查询比嵌套查询速度快很多。

嵌套select语句也叫子查询,一个 select 语句的查询结果能够作为另一个语句的输入值。子查询不但能够出现在where子句中,也能够出现在from子句中,作为一个临时表使用,也能够出现在select list中,作为一个字段值来返回。

  • 单行子查询

单行子查询是指子查询的返回结果只有一行数据

当主查询语句的条件语句中引用单行子查询结果时可用单行比较符号来进行比较

单行比较符号

=  !=
>  >=
<  <=

例如

select ename,deptno,sal
from emp
where deptno=(select deptno from dept where loc='NEW YORK')
  • 多行子查询

多行子查询即是子查询的返回结果是多行数据(组成的表)

当主查询语句的条件语句中引用多行子查询结果时必须用多行比较符号来进行比较

多行比较符号

in
all
any

例如

  • in

查询所有部门编号为A的资料:

select ename,job,sal
from emp
where deptno in (
    		select deptno  -- 查询部门A的所有资料号码
    		from dept
    		where dname like 'A%'
		)
  • all

查询有一门以上的成绩高于Kaka的最高成绩的学生的名字

select stName
from Student
where stId in(
             select distinct stId 
    	     from score 
    	     where score > all(
                 	      select score -- 高于Kaka的所有成绩,就高于最高成绩
                 	      from score 
                 	      where stId = (
                                           select stId 
                                  	   from Student 
                                  	   where stName = 'Kaka'
                              		   )
             		      )
	     )
  • any

查询有一门以上的成绩高于Kaka的任何一门成绩的学生的名字

select stName
from student
where stId in(
	     select distinct stId
	     from score
	     where score > any (
			       select score
	                       from score
		               where stId = (
			                    select stId
		                            from student
			 		    where stName = 'Kaka'
		          	            )
			       )
    	     )

级联查询

级联查询包含

inner join -- 根据连接条件(on) 可以分成等值连接和不等值连接
left join -- 左外连接,返回左表中的所有行,如果左表中行在右表中没有匹配行,则结果中右表中的列返回空值
right join -- 右外连接,返回右表中的所有行,如果右表中行在左表中没有匹配行,则结果中左表中的列返回空值
full join -- 全外连接,返回两个表中的所有行,如果存在某一个行不能匹配,则为空值
cross join -- 笛卡尔积
---- suffer now and live the rest of your life as a champion ----
原文地址:https://www.cnblogs.com/popodynasty/p/13828541.html