2014/11/24 条件查询

一、多个条件查询:in、between
    select * from category where parent='013' or parent='12' or parent='011'
等于select * from category where parent in ('011',''012','013')
in相当于多个 or
若查询不在“in”范围内的,in前面加 not ,即 not in
    select * from category where ids>500 and ids<505
等于select * from category ids between 500 and 505
小的数必须在between后面,表示大于等于500,小于等于505.

二、模糊查询:like
select * from category where name like '%国家%'
查找name中带有“国家”的信息。
%代表“国家”前、后可以有任何字符。

select * from category where name like '%机构’
查询以“机构”结尾的信息

三、只查某列数据:any
select code,name from category
select * from category where Ids > any (select * from category where Ids>1190 and Ids<1195))
any 代表任意一个,与其对应的为 all

四、排序:order by
select * from category order by Ids (句尾默认有asc→升序,对应的为desc→降序)
表示查询Ids,并按照升序排列
对两列排序的,先排parent(上一级),后排Ids,即:
select * from category order by parent,Ids
若想两列都为降序,需在parent和Ids后分别加desc;
若只在句末加desc,则只对句末的列降序

五、分组:group by
select * from category group by parent
group by表示这一列相同值的分为一组
整个语句可以理解为,显示含有下一级的数据,不含有下一级的不会被查询出。

六、去重:distinct
select distinct parent from category
表示category中去除重复的查询出来。

七、查询前xx条信息
select top5 * from category
select top5 * from category order by ids  表示ids排序后显示前5条信息

语句执行的条件:
先选择条件→再排序→再显示出

 

 

例题:

 

查询前5-8名同学的信息,并按身高排序

select top 3 * from student where code not in(select top 5 code from student order by stature desc,code desc)

order by stature desc

降序排列stature,code→除去前5名的信息→降序排列stature,code→从除去第五名后的第六名开始→显示前3名

 

查询男同学的身高高于所有女同学的同学的信息

select * from student where sex='男' and stature>all (select stature from stature from student where sex='女')

posted @ 2014-11-24 14:43  雪山飞驴  阅读(107)  评论(0编辑  收藏  举报