基础的增删改查操作
1.增操作
1.insert into 表名 set name='stu1',age=19;
2.insert into表名 (name,age) VALUES('stu2',20) ;
3.insert into表名 (name,age) VALUES('stu3',20),('stu4',21),('stu5'.22);
2.删除操作
1.delete from 表名
全部删除
2.delete from 表名 where name=" "
删除选中的一行
3.delete from 表名 order by xxx;
Order by代表删除数据的顺序,通常和limit 配合使用
4.delete from 表名 limit 1;
Limit子句代表被删除数据的行数限制
3.修改操作
update t_user set name="张三" where name='wangzhen' (修改)
4.查询操作(含sql自带函数)
1.select \* from 表名 where 列名=' ' ;
2.select * from 表名 where 列名=’ ';
函数拓展
一、数学函数
1.ROUND四舍五入
select round(1.23);
2.ROUND指定保留位数的四舍五入
select round(1.2345,3);
3.CEIL向上取整
select ceil(1.23);
4.FLOOR向下取整
select floor(9.99);
5.TRUNCATE截断
select truncate(1.4499,2);
6.MOD取模
select mod(-10,-3);
7.ORDER–BY DESC倒序排序
select \* from student order by age desc;
8.ORDER–BY ASC正序排列
select \*from stu order by age asc;
二、聚合函数
1.AVG返回平均值
select avg(age) from stu;
2.COUNT返回指定列中非NULL值的数量
select count(age) from stu;
3.COUNT返回表的行数(包含有NULL值的列)
select count(\*) from stu;
4.MAX返回最大值
select max(age) from stu;
5.MIN返回最小值
select min(age) from stu;
6.SUM求和
select sum(age) from stu;
三、流程控制语句(if、case)
1.IF 语句
select if(10\>5,'大于','不大于');
2.CASE-----WHEN
类似switch—case
select age,(
case id //列名
when 5 then '5'
when 6 then '6'
else 'other'
END
)as isyoung
from stu;
四、字符、字符串相关函数
1.UPPER小写字母转为大写字母
select upper('sp');
2.LOWER大写字母转小写字母
select lower('SP');
3.ASCII返回字符ASCII码
select acsii('A');
4.SUBSTRING截取字符串
select substring('sphxhxx',1,3);
5.LEFT / RIGHT从左侧/右侧截取字符串
select left(‘ilove’,3);
select right(‘study’,2);
典型实例
1.insert count(\*) AS num from student; (统计行数,AS 以什么命名)
2.select sum(列名) from 表名;
select sum(age) from student; (查找中age 最大的数据)
3.select avg(列名) from 表名;
select avg(age) from student; (统计表中age的平均值)
4.select * from 表名 order by 列名 asc;
select \* from student order by age asc;(asc 升序 默认顺序 可以不写)
5.select * from 表名 order by 列名 desc;
select \* from student order by age desc;(desc 降序)
补充:
关于order by:
order by 语句用于根据指定的列对结果集进行排序,默认按照升序排列。
1. select 字段名 from 表名 where 条件 order by 字段名1 asc/desc, 字段名2
asc(升序,默认)/desc(降序),.......
2. select 字段名 from 表名 where 条件 order by 字段序号 asc/desc, 字段序号
asc/desc,....... (字段序号从1开始)
最后要注意order by的在使用时,写在前面的字段会先执行,例如:
SELECT sno,sname,sex,brithday,dno FROM student ORDER BY 4,5DESC;
这句对第四列(日期列)优先升序排列(默认),只有该列有相同值(1983-10-04)时,第5列才会按照语句进行降序排列。
SELECT sno,sname,sex,brithday,dno FROM student ORDER BY 5,4 DESC;
第5列升序