上一章 说了下 子查询的意义是 把一条查询语句当做值来使用
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
原文:http://www.cnblogs.com/zhangwei99com/p/6542088.html