目录
1、select
显示表格中的一个或者多个字段中所有的信息
#语法:
select 字段名 from 表名;
示例1:
select * from info1;
示例二:
select name,age from info;
2、distinct
查询不重复记录
#语法:
select distinct 字段 from 表名﹔
#示例1:去除年龄字段中重复的
select distinct class from info1;
#示例2:查找性别
select distinct gender from info;
3、where
where 有条件的查询
#语法:
select ‘字段’ from 表名 where 条件
#示例:显示name和age 并且要找到age小于20
select name,age from info1 where age < 20;
4、and;or
and 且 ; or 或
#语法:
select 字段名 from 表名 where 条件1 (and|or) 条件2 (and|or)条件3;
select name,age from info1 where age >20 and age <30;
5、in
#语法:
select 字段名 from 表名 where 字段 in (‘值1’,‘值2’…);
#示例1:显示学号为1,2,3,4的学生记录
select * from info1 where id in (1,2,3,4);
#示例2:显示班级为2和5的学生记录
select * from info1 where class in (1,3);
6、between
#语法:
select 字段名 from 表名 where 字段 between ‘值1’ and ‘值2’;
包括 and两边的值
#示例1:显示学生号码id在2-5 的信息
select * from info1 where id between 2 and 5;
#示例2:显示学生年龄在20-35之间的信息,不需要表中一定有该字段,只会将20到25 已有的都显示出来
select * from info1 where age between 20 and 25;
7、like 通配符
通配符通常是和 like 一起使用
#语法:
select 字段名 from 表名 where 字段 like 模式
#示例1:查找名字以w开头的学生记录
select * from info1 where name like 'w%';
#示例2:查找名字包含ng的学生记录
select * from info1 where name like '%ng%';
#示例3:查找名字第二个字母为a,第三个字母为n的学生记录
select * from info1 where name like '_an%';
8、order by
#语法:
select 字段名 from 表名 where 条件 order by 字段 [asc,desc];
asc :正向排序
desc :反向排序
默认是正向排序
#示例1:按学生的年龄正向排序显示年龄和姓名字段
select age,name from info1 order by age;
#示例2:按学生的年龄反向排序显示年龄和姓名字段
select age,name from info1 order by age desc;
#示例3:显示name、age和class字段的数据 并且只显示class字段为2 的 并且以age字段排序
select age,name,class from info1 where class=2 order by age;
9、函数
(1)数学函数
#示例1:返回-2的绝对值
select abs(-2);
#示例2:随机生成一个数
select rand (1);
#示例3:随机生成排序
select * from info1 order by rand();
#示例4:返回7除以2以后的余数
select mod(7,2);
#示例5:返回2的3次方
select power(2,3);
#示例6:返回离2.6最近的数
select round(2.6);
#示例7:保留2.335321的3位小数四舍五入后的值
select round(2.335321,2);
#示例8:返回数字 2.335321 截断为2位小数的值
select truncate(2.335321,2);
#示例9:返回大于或等于2.335321 的最小整数
select ceil(2.335321);
#示例10:返回小于或等于 2.335321 的最大整数
select floor(2.335321);
#示例11:返回集合中最大的值
select greatest(1,4,3,9,20);
#示例12:返回集合中最小的值
select least(1,4,3,9,20);
(2)聚合函数
#示例1:求表中年龄的平均值
select avg(age) from info1;
#示例2:求表中年龄的总和
select sum(age) from info1;
#示例3:求表中年龄的最大值
select max(age) from info1;
#示例4:求表中年龄的最小值
select min(age) from info1;
#示例5:求表中有多少班级字段非空记录
select count(class) from info1;
count(明确字段):不会忽略空记录
#示例6:求表中有多少条记录
select count(*) from info1;
count(*)包含空字段,会忽略空记录
#示例7:看空格字段是否会被匹配
insert into info1 values(26,' ',28,'男',1);
(3)字符串函数
trim
语法:
select trim (位置 要移除的字符串 from 字符串)
其中位置的值可以是
leading(开始)
trailing(结尾)
both(起头及结尾)
#区分大小写
要移除的字符串:从字符串的起头、结尾或起头及结尾移除的字符串,缺省时为空格。