MySQL数据库指令集
增(insert)
不指定字段
insert into values(值1,值2,值3...);
指定字段(没给到值的字段为默认值或null)
insert into [(字段1,字段2,字段3,...)] values(值1,值2,值3...);
insert与子查询(插入多条数据)
insert into
;
replace插入
用法与insert基本相同,如:replace into values(值1,值2,值3...);,不同的是如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。否则,直接插入新数据。
注意:因为要根据主键或者是唯一索引判断是否有重复数据,所以操作的表必须要有主键或者是唯一索引。否则的话,replace into 会直接插入数据。
删(delete)
常用删除语句
delete from [where condition];
delete与子查询(删除多条数据)
delete from
where 字段=;
truncate清空表记录
truncate table ;
改(update)
常用更新语句
update set 字段1=值1,字段2=值2...
[where condition];
update与子查询(修改多条数据)
update set 字段1=值1,字段2=值2...
where 字段=;
查(select)
常用查询语句
select [distinct] [,]
from [,]
[where ]
[group by [having ]]
[order by[asc|desc]]
[limit [start,]count]
distinct关键字
这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是distinct只能返回它的目标字段,而无法返回其它字段
[where ]
1.关系表达式查询
关系运算符:=(等于)、>(大于)、=(大于等于)、<=(小于等于)、!=或<>(不等于)
eg:select name from user where id>10;
2.逻辑表达式查询
逻辑运算符(优先级从高到低):not、and、or
eg:select * from user where name='simu' and age=20;
3.设置取值范围的查询
谓词:between ... and ... 或 not between ... and ...
eg:select * from user where id between 10 and 20;
4.空值查询
谓词:is null 或 is not null
eg:select * from user where id is null;
5.模糊查询
SQL通配符:
1、%:代表任意多个字符。
2、_(下划线):代表任意一个字符。
谓词:like 或 not like
eg:select * from user where name like 'simu';
分组查询-[group by [having ]]
聚合函数
SUM():返回某列所有值的总和
AVG():返回某列的平均值
MAX():返回某列的最大值
MIN():返回某列的最小值
COUNT():返回某列的行数
group by 子句:将根据所指定的列对结果集中的行进行分组。
having 子句:以组为对象进行筛选。
eg:select role count(*) as 总数 from user group by role having count(*)>0
[order by[asc|desc]]
根据查询结果中的一个或多个字段对查询结果进行排序。默认升序asc;
eg:select name,money from user order by money desc;
[limit [start,]count]
从结果集中进一步选取指定数量的数量,默认值为0,即第1行数据为0。
eg:select name,money from user order by money desc limit 5;