SQL子查询
概念:
子查询就是可以嵌套到如何允许使用表达式的地方均可使用子查询。嵌套的地方又是一个查询。
1、单行子查询
语法:
select * from [table] where column=(select column from column2=值)
子查询的使用经验:
- 子查询通常用在位于select语句的where子句中,且可以嵌套。
- 编写复杂可以逐层分解查询,从最内层的子查询开始,遵循“由内及外”的原则。
- 一般情况,连接查询可改为子查询实现,子查询不一定可以用连接查询实现。
- 子查询与连接查询执行效率:当子查询执行结果的行数较大,而主查询执行结果的行数较小时,子查询执行效率较高。
2、多行子查询
in比较符:in比较符就相当于or的用法。
select * from [table] where col1=值1 or col1=值2 or col1=值3
与
select * from [table] where col1 in(值1,值2,值3)
它们是一个意思
1.多行子查询:
语法:
select * from [table] where col1 in(select col1 from [table1] where col=值)
这是比较简单的多行子查询
2.all关键字子查询
select * from [table] where col>all(select col from [table1] where col2=(select col2 from [table2] where col3=值))
all的含义:
- <all,表示小于最小值
- .> all,表示大于最大值
3.除了在where子句中还可以在select子句中:
select col1,(select col2 from [table]) from [table]
4.exists关键字:
概念:exists是用于检查子查询是否至少返回一行数据的,如果返回一条数据就会返回true否则为false。
语法:
select * from [table] t1 where exists (select * from orders where col1=t1.col1)