-- 不带条件修改数据,将所有的性别改成女update student set sex='女'-- 带条件修改数据,将id号为2的学生性别改为男update student set sex='男'where id=2;-- 一次修改多个列,把id为的学生年龄改成26岁,address改成北京update student set age=16,address='北京'where id=3;
删除表记录
不带条件删除数据
deletefrom 表名;
带条件删除数据
deletefrom 表名 where 字段名=值;
使用truncate删除表中所有记录
truncatetable 表名;
truncate和delete的区别
truncate相当于删除表的结构,再创建一张空表
例子
-- 条件删除数据,删除id为1的记录deletefrom student where id=1;-- 不带条件删除数据,删除表中的所有记录deletefrom student;
-- 1.查询所有学生select*from student;-- 2.查询student表中的name和age列select name,age from student;-- 3.使用别名select name as 姓名,age as 年龄 from student;-- 4.表使用别名select st.name as 姓名, age as 年龄 from student as st;#表使用别名的原因:用于多表查询操作
清除重复值
查询指定列并且结果不出现重复数据
selectdistinct 字段名 from 表名;
例子
-- 查询学生来自哪些地方select address from student;-- 去掉重复的记录selectdistinct address from student;
查询结果参与运算
某列数据和固定值运算
select 列名1+固定值 from 表名;
某列数据和其他列数据参与运算
select 列名1+列名2from 表名;#参与运算的必须是数值类型
例子
select*from student;-- 给所有的数学加5分select math+5from student;-- 查询所有学生信息,math+english的和select*,(math+english)as 总成绩 from student;-- as可以省略select*,(math+english) 总成绩 from student;
在一个范围之内,如:between 100 and 200 相当于条件在100到200之间,包头又包尾
>,<,<=,>=,=,<>
<>在SQL中表示不等于,在mysql中也可以使用!=,没有==
in(集合)
集合表示多个值,使用逗号分隔
like’张%’
模糊查询
is null
查询某一列为null的值,注不能写成=NULL
逻辑运算符
说明
and 或 &&
与,SQL中建议使用前者,后者并不通用
or 或
或
not 或 !
非
例子
-- 查询math分数大于80分的学生select*from student where math>80;-- 查询english 分数小于等于80分的学生select*from student where english <=80;-- 查询age等于20岁的学生select*from student where age=20;-- 查询age不等于20岁的学生select*from student where age !=20;select*from student where age <>20;-- 查询age大于35且性别为男性的男生select*from student where age>35and sex='男';-- 查询age大于35或性别为男的学生select*from student where age>35or sex='男';-- 查询id是1或3或5的学生select*from student where id=1or id=3or id=5;
in关键字
select 字段名 from 表名 where 字段 in(数据1,数据2,...);#in 里面的每一个数据都会作为一次条件,只要满足条件的就会显示
例子
-- 查询id是1或3或5的学生select*from student where id in(1,3,5);-- 查询id不是1或3或5的学生select*from student where id notin(1,3,5);
范围查询
between 值1 and 值2
表示从值1到值2范围,包头又包尾
-- 查询english成绩大于等于75,且小于等于90的学生select*from student where english between75and90;
like关键字
like表示模糊查询
select*from 表名 where 字段名 like'通配字符串';
MySQL通配符
通配符
说明
%
匹配任意多个字符串
_(下横杠)
匹配一个字符
例子
-- 查询姓马的学生select*from student where name like'马%';-- 查询姓名中包含'德'字的学生select*from student where name like'%德%';--查询姓马,且姓名有两个字的学生select*from student where name like'马_';