增
1、向表内增加字段,用alter table + 表名 + add + 字段名 + 类型 + 约束条件;
alter table student add birthday date not null;
2、向表内插入部分数据用insert into 表名 (字段1,字段2) values (数据1,数据2);
需要注意的是,除插入的这一部分数据外,其他字段的数据必须允许为空或有默认值方可使用这一方法
insert into student(name, age) values ('李四',20);
3、向表内一次性插入多条数据,用insert into 表名 values(数据1),(数据2);
Insert into student values(0,'王五',15,2,156.78,3),
(0,'赵六',17,'女',167.99,2);
4、在字段类型为枚举(enum)时,添加该字段数据时可以用枚举中的值,也可以用下标(下标从1开始)
删
1、删除字段用alter table 表名 drop 字段;
删除字段后,字段下的数据也会被删除掉
alter table student drop birthday;
2、删除表用drop table 表名;
drop table student;
3、删除数据用delete from 表名 + 约束条件;
delete from student where id=2;
4、数据的逻辑删除,即在原表中添加一列二进制类型的字段,用0和1分别表示该行数据是否删除,届时根据实际情况更新即可
alter table student add is_delete bit default 0;
改
1、修改字段类型/约束(不需重命名)alter table 表名 modify 字段名+类型+约束
alter table student birthday date;
2、修改字段类型/约束且重命名alter table 表名 change 旧字段名+新字段名+类型+约束
alter table student birthday birth date not null;
3、修改数据 update 表名 set 字段=新值 where 条件;
如果不加where进行约束,则整个字段的数据都会重新被赋值
update student set age=15 where id=1;
查
1、查看数据表创建信息用show create table + 表名;
与数据库操作的show create database类似,都可以查看创建时的设定
如果有设置某个字段(如主键)的约束为auto_increment,那么在此处则会显示下一条数据插入时该字段的值。除非在插入时填写的该字段数值大于这个值,否则都为这个值
2、查看表中部分数据用select * from 表名 where 指定条件;
*表示查询所有字段
select * from student where gender=1;
3、查看表中指定字段的数据用select 字段1, 字段2 from 表名 where 指定条件;
select name, cls_id from student where id=3;
4、将查询出来的数据修改表头用select 字段1 as 别名1, 字段2 as 别名2 from 表名;
后面也可以加上条件筛选限定,且语句中字段的先后顺序与查询出的表格内字段的顺序一致
select name as '姓名', gender as '性别' from student;
5、查询时也可以通过给表格起新的表名来缩短语句,在连接查询中的用处比较大
select s.name, c.name from student as a inner join classes as c on s.cls_id=c.id;
6、查询出某个字段去重后的结果,用select distinct 字段 from 表名;
select distinct cls_id from student;