1、增加数据
insert 语句可以用来将一行或多行数据插到数据库表中, 使用的一般形式如下:
Insert into 表名(字段列表) values (值列表);
insert [into] 表名 [(列名1, 列名2, 列名3, ...)] values (值1, 值2, 值3, ...);
insert into students values(NULL, "张三", "男", 20, "18889009876");
有时我们只需要插入部分数据, 或者不按照列的顺序进行插入, 可以使用这样的形式进行插入:
insert into students (name, sex, age) values("李四", "女", 21);
2、查询数据
select 语句常用来根据一定的查询规则到数据库中获取数据, 其基本的用法为:
select 字段名 from 表名称 [查询条件];
查询学生表中的所有信息:select * from students;
查询学生表中所有的name与age信息:select name, age from students;
也可以使用通配符 * 查询表中所有的内容, 语句: select * from students;
2.1、表达式与条件查询
where 关键词用于指定查询条件, 用法形式为: select 列名称 from 表名称 where 条件;
以查询所有性别为女的信息为例, 输入查询语句: select * from students where sex="女";
where 子句不仅仅支持 "where 列名 = 值" 这种名等于值的查询形式, 对一般的比较运算的运算符都是支持的, 例如 =、>、<、>=、<、!= 以及一些扩展运算符 is [not] null、in、like 等等。 还可以对查询条件使用 or 和 and 进行组合查询, 以后还会学到更加高级的条件查询方式, 这里不再多做介绍。
示例:
查询年龄在21岁以上的所有人信息: select * from students where age > 21;
查询名字中带有 "王" 字的所有人信息: select * from students where name like "%王%";
查询id小于5且年龄大于20的所有人信息: select * from students where id<5 and age>20;
2.2、聚合函数
获得学生总人数:select count(*) from students获得学生平均分:select avg(mark) from students获得最高成绩:select max(mark) from students获得最低成绩:select min(mark) from students获得学生总成绩:select sum(mark) from students
3、删除数据
delete from 表名 [删除条件];
删除表中所有数据:delete from students;
删除id为10的行: delete from students where id=10;
删除所有年龄小于88岁的数据: delete from students where age<88;
4、更新数据
update 语句可用来修改表中的数据, 基本的使用形式为:update 表名称 set 列名称=新值 where 更新条件;Update 表名 set 字段=值 列表 更新条件
使用示例:
将id为5的手机号改为默认的"-": update students set tel=default where id=5;将所有人的年龄增加1: update students set age=age+1;将手机号为 13723887766 的姓名改为 "张果", 年龄改为 19: update students set name="张果", age=19 where tel="13723887766";
5、修改表
alter table 语句用于创建后对表的修改, 基础用法如下:
5.1、添加列
基本形式: alter table 表名 add 列名 列数据类型 [after 插入位置];
示例:
在表的最后追加列 address: alter table students add address char(60);
在名为 age 的列后插入列 birthday: alter table students add birthday date after age;
5.2、修改列
基本形式: alter table 表名 change 列名称 列新名称 新数据类型;
示例:
将表 tel 列改名为 phone: alter table students change tel phone char(12) default "-";
将 name 列的数据类型改为 char(9): alter table students change name name char(9) not null;
5.3、删除列
基本形式: alter table 表名 drop 列名称;
示例:
删除 age 列: alter table students drop age;
5.5.4、重命名表
基本形式: alter table 表名 rename 新表名;
示例:
重命名 students 表为temp: alter table students rename temp;
5.5、删除表
基本形式: drop table 表名;
示例: 删除students表: drop table students;
5.6、删除数据库
基本形式: drop database 数据库名;
示例: 删除lcoa数据库: drop database lcoa;