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 <表名>;
改(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.模糊查询
谓词:like 或 not like
eg:select * from user where name like 'simu';