单表查询DQL

基本数据检索:单表

复杂数据检索:多表:连接查询、子查询(嵌套查询)、集合运算

基本select语句:

  • select <检索字段>
  • from <表>
  • where <检索条件>
  • group by<分类>
  • having<检索条件>
  • order by <排序字段>

操纵列:

  • 1.输出所有列:select *
  • 2.输出指定列:select <字段>[,...n]
  • 3.计算表达式:select <表达式>[,...n]
  • 4.设置列表标题名:<表达式> [AS] <别名>|<别名>=<表达式>
  • 5.消除重复记录:distinct
 1 select * from <表名>     --查询表中所有数据
 2 
 3 select <字段名>,<字段名>  form <表名>   --投影
 4 
 5 select <表达式> from <表名>  --查询计算列
 6 --eg:表达式为:2020-sage    sage为字段名
 7 --:select 2020-sage from 表名
 8 
 9 --计算列没有名称,通常需要  命别名
10 --1.字段 as 别名 :           select 2020-sage as 别名 from 表名
11 --2.字段 别名,即as 可省:     select 2020-sage  别名 from 表名
12 --3.别名=字段:               select 出身年=2020-sage  from 表名
13 
14 select [谓词] 字段 from 表名
15 --1. distinct 去重 :        select distinct 2020-sage as 别名 from 表名

操作行

1.普通查询:where <逻辑表达式>

2.模糊查询:1. 运算符 like   2.通配符 :%任意个字符,_任意一个字符

select [谓词] 字段 from 表名
--2.top  n:查询记录的前n行
select top 3 * from 表名     --选择前 n 行
--3.top  n percent :查询前n%行
select top 3 percent * from 表名     --选择前 n% 行

select top n percent 字段 fromwhere 表达式 order by 排序字段名 [asc]/desc
--order 默认的排序方式是升序asc,可不写

select top n percent with ties 字段 fromwhere 表达式 order by 排序字段名 [asc]/desc
--with ties 显示排序字段的并列值
--eg: top 3 :但第三名与第四名排序字段相同,则with ties 使第三名和第四名都显示出来

--in /not in (子查询/表达式列表)  :过滤记录
select  * from 表名 where grade in (88,99)

--between/not between  起始值 and 终止值 :过滤记录
select  * from 表名 where grade between 80 and 90

--字段 like '正则表达式' :模糊匹配
select * from where 学号 like '%[1,4]'  --匹配以1,或4结尾的学号

分组查询

group by 分组字段

聚合函数

select count(字段名)  fromgroup by 分组字段   --查找每个分组的记录数量
--当使用 count(*)时,统计所有记录
--当使用 count(字段名)是,统计记录不包含null
--当使用 count(distinct 字段名)时,统计记录不包含重复和null

 

若分组增加条件则使用 having,可在汇总后过滤

即,分组之前的条件使用where ,分组之后的条件使用having

 

 

 

猜你喜欢

转载自www.cnblogs.com/yrxc/p/12946043.html