SQL server 数据库基础语句 子查询 基础函数

上一章 说了下   子查询的意义是 把一条查询语句当做值来使用

select *from car   //查询汽车的信息 

假设我知道一个汽车的编号是 c021

但是我要查询 比这个汽车价格高的汽车信息

先找到汽车编号是c021的   select *from car where code='c021'

在找这个汽车的价格        select price from car  where code='c021' //返回的是价格这个值

这个值是 31.75  

那么我要找比这个价格高的汽车信息  select *from car where price >31.75

那么我要把31.75 换成上面的信息   那么语句合并写为

select *from car where price >(select price from car where code='c021')

那么这里的括号里面的就是子查询语句

但是子查询  查询出来的有时候不一定是一个值  而是多个值  那怎么办呢

那我们要用到子句查询 

子句查询查询查出来的结果不一定是一个数  有可能是多个数  但是必须是一列

例如 我要查油耗 为7.4  8 8.2 的汽车信息

select *from car where oil=7.4 or oil =8 or oil 8.2    多写的话有点麻烦

这里要学到新的词句   改写为select *from car where oil  in ( 7.4 , 8 , 8.4 ) 、

 意思是   油耗 满足 (7.4 ,8 ,8.4)任意一个值的信息拽出来

或者用code为c016  c029 c014查询油耗的汽车信息

select  oil from car where code in('c016','c029','c014')   返回的值也是 油耗 7.4   8   8.4

我要用code 查询油耗为(7.4    8   8.4)的汽车所有信息

select *from car where oil in

(

select oil from car where code in ('c016','c029','c014')

)

注意:语句可以换行   但是C#中不能换行   这里的语句后面可以加上--(双减号)代表的是注释

子句查询可以返回多行数据  但必须是一列

这里的   in不是代表的  or  

例如  select *from where oil not in (7.4,8,8.4) 可以理解为都不满足   

区间

查询油耗为7和8之间的   

之前的是    select  *from car where oil>=7 and oil<=8

现在写为    select  *from car  where oil between 7 and 8

 any 任意  all所有 

select * from car where code in ('c016','c029','c014')

select *from car where oil > any (select oil from car where code in ('c016','c029','c014'))  //大于任意一个

但是还有最大那个

>any或者<any 的时候      any 是任意的意思        大于这一堆数据最小的那个    小于最大的

all   >all或者<all              al是所有                      大于或者小于包含all里面的数据  

两个表拼接

例如我要用car的name 和brand 的 name拼接

图中brand_code和car的brand 有关联

那么   select  name,(select brand_name from brand where brand_code=car.brand) from car

 

原文地址:https://www.cnblogs.com/zhangwei99com/p/6542088.html