7:表数据的增删查改
-
mysql的服务器,本质是在内存中的,所有数据库的CRUD操作,都是在内存中进行的。
1. 增加(create):
insert into xxx (字段1,字段2,字段3) values (值1,值2,值3); // 单行,指定列插入
insert into xxx (字段1,字段2,字段3) values (值1,值2,值3),(值1,值2,值3); // 多行,指定列插入
insert into xxx values (值1,值2,值3); // 全插入,into可省略
insert into xxx values (值1,值2,值3),(值1,值2,值3); // 多行,全插入
2. 更新:
insert into xxx values (值1,值2,值3) on duplicate key update 字段x=值x...;
//如果不存在数据便直接插入,如果存在数据便修改为指定数据。
3. 替换:
replace into xxx values (值1,值2,值3);
// 替换,如果主键或者唯一键不冲突就插入,如果主键或者唯一键有冲突就替换。
1. 查询:
select * from xxx; // 全查询,数据越多,传输量越大
select 字段1,字段2 from xxx; // 从xxx表中只查询指定字段的数据
select 字段1+字段2 as 新名称 from xxx; //将xxx表中的字段1和字段2计算的结果重命名输出。
2. where子句:
select name from xxx where name like '孙%'; // 模糊匹配查找xxx中所有姓孙的同学
select name from xxx where chinese>english; // 查找所有语文成绩高于英语的同学
select name,chinese from xxx where chinese > 80 and name not like '孙%';
//查找所有语文成绩低于80且不姓孙的同学
3. order by排序:
-
如果没有经过order by进行排序,那么返回结果的顺序是随机的。
-
asc升序,desc降序,默认为esc。
-
null值参与排序,但是它小于任何一个值。
select name,math from xxx order by math asc; // 通过数学成绩升序排序同学。
select name,math,chinese,english from xxx order by math desc, chinese asc, english asc;
//按照数学降序,语文升序,英语升序的方式排列。
select name,math+chinese+english as total from xxx order by total asc;
//升序排序总成绩,可以使用别名进行排序
select name,math from xxx where name like '孙%' or name like '曹%' order by math asc;
//查询姓孙或者姓曹的同学的数学成绩,按照数学成绩升序排序。
4. 筛选(limit):
select name,math from xxx order by math asc limit 5; // 查询前5行
select name,math from xxx order by math asc limit 2,4; // 查询从第2行后的4行,不包括第2行
-
对未知表进行查询时,加上limit做限制,防止数据量过大导致数据库卡死。
1. 更新(update):
-
对查询到的结果进行列值更新,配合查找使用。
update xxx set 字段1=值1 where ...; // 将xxx表通过where查到的数据的math全部改为80
update xxx set 字段1=值1,字段2=值2 where ...; // 将xxx表中where查到的数据的多个字段的值进行修改,逗号分隔
update xxx set math=math+30 order by math+chinese+english asc limit 3;
//将总分后三名的同学的数学成绩加上三十分
1. 删除(delete):
delete from xxx; // 将xxx表中的所有数据全部删除,但是保留表结构
delete from xxx where ...; // 根据where查询进行删除
delete from xxx order by 表达式 asc limit 1; // 根据排序删除,将表达式排序的结果的第一行删去
truncate xxx; // 删除xxx表中的所有数据。
-
delete from删除整张表,不会重置auto_increment的值。
-
truncate删除整张表的数据,会重置auto_increment的值。速度比delete from快。