一、DML:增删改表中数据
1、insert
insert into 表名(列名1,列名2,…列名n) values(值1,值2,…值n);
insert into 表名 values(值1,值2,…值n);
2、delete
delete from 表名 [where 条件]
如果要删除所有记录:(仅仅删除记录,而不是删除表)
(1)delete from 表名; – 不推荐使用。有多少条记录就会执行多少次删除操作(不加where条件,会删除所有记录)
(2)truncate table 表名; – 推荐使用,效率更高 先删除表,然后再创建一张一样的表。
3、update
update 表名 set 列名1 = 值1, 列名2 = 值2,… [where 条件];
二、DQL:查询
基础查询
1、查询表中所有数据:
select * from stu;
2、查询姓名,年龄:
select name,age from stu;
3、查询后的地址去重复:
注意:如果有重复,说明多了空白字符(比如空格)
select distinct address from stu;
select distinct name,address from stu; //多个字段相同才去重
4、计算math和english的和
select math+english from stu; //一方有null,结果为null
select math+ifnull(english,0) from stu; //去除null
5、起别名
select name as 名字 from stu;
select name 名字 from stu; //as可以省略
条件查询
1、查询年龄大于等于小于30岁的所有信息
注意:>、>=、<、<=、=、!=、<>
等于是一个等号
select * from stu where age > 30;
2、区间查询 [20,30] -----且
select * from stu where age >= 20 && age <=30;
select * from stu where age >= 20 and age <=30;
select * from stu where age between 20 and 30;
3、具体查询22,18,30 -----或
select * from stu where age = 22 or age = 18 or age = 30;
select * from stu where age in (22,18,30);
4、查询null值
注意:null不能用=和!=比较
select * from stu where english is null;
select * from stu where english is not null;
模糊查询:
_:单个任意字符
%:多个任意字符(可以是0个)
1、查询姓马的人
select * from stu where name like '马%';
2、查询姓名第二个字是化的人
select * from stu where name like '_化%';
3、查询姓名为三个字的人(注意:若查到两个字,说明有空字符)
select * from stu where name like '___';
4、查询姓名中包含德的人
select * from stu where name like '%德%';
***排序查询:
升序ASC:默认
降序DESC
***
select * from stu order by math asc , englist asc;//按数学升序排序,数学一样,再按照英语
聚合函数
1、count(*)或count(主键)--------统计表中记录数量
2、max、min
3、sum、avg
分组查询
1、按照性别分组,分别查询男、女同学的数学平均分、人数
select sex,avg(math),count(id) from stu group by sex;
查询结果:
2、按照性别分组,分别查询男、女同学的数学平均分、人数;要求:分数小于70的人不参与分组
select sex,avg(math),count(id) from stu where math >= 70 group by sex;
查询结果:
3、按照性别分组,分别查询男、女同学的数学平均分、人数;要求:分组之后,人数大于两个人
select sex,avg(math),count(id) from stu group by sex having count(id) > 2;
查询结果:
总结:
where是在分组之前进行限定
having是在分组之后进行限定