一.基础格式 select <字段名> from <表名>
1.选择多个字段用逗号隔开(一定要英文的)
2.select * from <表名> 选择整个表
3.select后可以跟计算字段,四则运算如(gdp/population+1)、sum(gdp)、max()、avg()、min()都可以直接用。
二.重命名 select <字段名> as <重命名> from <表名>
可以将字段名和表名重命名,其中as通常省略。
三.数据重复去重 select distinct <字段名> from <表名>
1.例子:select distinct name,Chinese grade,Math grade from class1 这里对distinct后的三个字段都去重了
2.distinct不能放中间,如select name,distinct Chinese grade,Math grade from class1 from class1 错误
四.通过where筛选、限定
注意:where的条件可以有多个,where只有一个,用法:
1.select name from class1
where Chinese grade<60 (输出语文不及格的学生)
2.select name from class1
where Chinese grade between 90 and 100(输出语文优秀的学生)
3.select name from class1
where name =‘John’
4.select name from class1
where name in (‘John’,‘MIke’)
5.select name from class1
where name not in (‘John’,‘MIke’)
6.模糊查询
例子:
select name from class1
where name like _%n’
‘ % ’ 表示任意0个或多个字符。可匹配任意类型和长度的字符。
‘ _ ’是占位符,表示任意单个字符。
例子:
- ‘C%ia’ 可以表示’China‘、’Cambonia‘
- ’_ a%’ 表示第二个字符是a的任意字符串,如variable
- ’_ _ a’表示第三个字符是a且含三个字符的字符串,如‘tea’
- '%a%'含a的都查
7.多条件查询
- select name from class1
where name like ’%a%a‘ and Chinese grade<60 - 同时使用 and 和 or 时
select country from world
where(name like ’%a%a‘ and area>600000) or (name like ’c%a‘ and population>1300000000) and优先级大于or,可以使用括号看的清楚点
8.order by 排序
order by<字段名> desc/asc
desc降序,asc升序,一般asc省略不写
9.limit 限制行数
limit 1 取排名第一的,且仅取一个
limt a,b 取从a+1开始的b个对象
10.聚合函数和group by
-
聚合函数的用法:
Max 求最大 Min 求最小 Sum 求总和 Avg 求平均 Count 计算总行数
如果单独用聚合函数,不用group by,则不能既用聚合函数,又用字段,如 select name,sum(grape) from class1就会报错。
-
group by
-group by语句中select指定的字段必须是“分组依据字段”
常常和order by一起用, 其中order by 和limit ,group by是在select前运行的,因为没有select的数也可以作为order by和limit ,group by的对象 -
where在聚合运算前筛选,having在运算后,且having不能脱离group by,having只能作为分组依据的字段