2016/3/13 七种查询 (普通查询 条件查询 排序查询 模糊查询 统计查询 分组查询 分页查询 )

一句话概括的话,SQL作为结构化查询语言,是标准的关系型数据库通用的标准语言;

T-SQL 是在SQL基础上扩展的SQL Server中使用的语言


1,普通查询
#查询Info表中的所有列
select * from Info
#查询Info表中的Name和Code列
select Name,Code from Info

2,条件查询 关键字where
#查询Info表的左右列 限定范围 列名为p001
select * from Info where 列名="p001"
#查询条件之间并且的关系
select * from Info where Nation='n001'and Sex=true
#查询条件之间或的关系
select * from Info where Nation='n001'or Sex=true

3,模糊查询 关键字 where like
查询表中所有的列 并在AreaName列中模糊查询
%代表前后可以有任意多个字符
select * from Info where AreaName like Name='%中%'
_代表前或者后只能有一个字符
select * from Info where AreaName like Name='_中'

4,排序查询 关键字order by asc 默认升序 desc 降序
select * from Info order by Code asc
select * from Info order by Code desc
select * from Info order by Brand,Powers #按照两个列排序 Brand是主 Powers是次

5,统计查询(聚合函数) 关键字 count min max sum avg
select count(*)from Car #查询总条数 count()内是*比较耗时间 耗资源
select count(1)from Car
select count(Code)from Car
select Max(Price) from Car #查询最大值 Price列的最大值
select Min(Price) from Car #查询最小值 Price列的最小值
select avg(Price) from Car #查询平均值
select sum(Price) from Car #查询总和

Select Count (*)和Select Count(1)两着返回结果是一样的
假如表没有主键(Primary key), 那么count(1)比count(*)快,
如果有主键的话,那主键作为count的条件时候count(主键)最快
如果你的表只有一个字段的话那count(*)就是最快的
count(*) 跟 count(1) 的结果一样,都包括对NULL的统计,
而count(column) 是不包括NULL的统计

6,分组查询 关键字:group by having
#根据系列分组查看每组数据条数 注意Code Brand 后面的,号
select Code Brand,count(*)from Car group by Brand
#在sql server下 后面是by Brand 前面必须是Brand
#查询分组之后数据条数大于2的
select * from Car group by Brand having count(*)>2

7,分页查询 关键字:limit   分页规律(N-1)*5
#跳过零条数据,取五条数据
select * from Car limit 0,5
select * from Car limit 5,5
Sql server 里面是 skap 0 tick 5 跳过0条 取5条

原文地址:https://www.cnblogs.com/haodayikeshu/p/5273256.html