1、添加字段
create table t3(subject int); (创建表格)
alter table t3 add math int(10); (添加 math 字段)
alter table t3 add(chinese int(10),english int(20));
alter table t3 add physic int(10) after english; (添加字段放english后面)
alter table t3 add history int(10) first; (添加字段放第一个)
2、修改字段和类型
(1) change 可以修改列的类型和列名、位置
alter table t3 change subject ids int(20) after math;
alter table 表名 change 旧字段 新字段名字 类型 after 字段名;
(2)modify 只能修改字段的类型
alter table t3 modify history varchar(30);
alter table 表名 modify 字段 类型;
(3)删除字段
alter table t3 drop ids; (删除表格t3中ids字段)
3、插入数据(添加记录)
提醒:数据库中的类型分别有:
- CHAR类型:用于表示固定长度的字符串,需要指定长度。与VARCHAR不同,CHAR类型会分配固定长度的存储空间。
- DECIMAL/NUMERIC类型:用于表示精确的十进制数值,可以指定总位数和小数点后的位数。
- FLOAT/DOUBLE类型:用于表示浮点数(单精度/双精度)。
- DATE/DATETIME/TIMESTAMP类型:用于表示日期和时间。
- TEXT类型:用于存储较长的文本数据。
- INT类型:用于表示整数值。INT类型可以存储的整数范围根据字节长度的不同而变化。常用的INT类型包括INTEGER、TINYINT、SMALLINT、MEDIUMINT和BIGINT。
- VARCHAR类型:用于表示可变长度的字符串。VARCHAR类型需要指定最大长度,可以存储包含字母、数字和特殊字符的字符串。VARCHAR类型以实际存储的字符数为基础分配存储空间。
示例:库内新建表格t4
create table t4(id int, name varchar(20), sex enum('m','f'), age int);
(1)添加一条记录:
insert into t4(id,name,sex,age) values('1','tom','m','90');
insert into 表名(字段1,字段2,字段3,字段4) values('1','tom','m','90');
(2)添加多条记录
insert into t4(id,name,sex,age) values('2','jack','m','19'),('3','taisen','m','19'),('4','lili','m','19');
insert into 表名(字段1,字段2,字段3,字段4) values('2','jack','m','19'),('3','taisen','m','19'),('4','lili','m','19');
(3)用set 添加记录
insert into t4 set id=4,name="zhangsan",sex="m",age=21;
(4)更新记录(修改表内数据)
update t4 set id=6 where name="xiaoli";
update 表名 set 修改的字段 where 给谁修改;
(5)删除记录
delete from t4 where id=6; (删除部分记录)
delete from t4; (删除所有记录/删除表)
(6)复制数据
① 复制表结构+记录 语法:create table 新表 select * from 旧表;
create table new_t1 select * from t4;
② 复制单个字段和记录:
create table new_t2(select id,name from t4);
4、查询
语法: select 字段名称,字段名称2 from 表名 条件
(1)简单查询:
select * from t4;
(2)多字段查询:
select id,name,sex from t4;
(3)按条件查询:
(where)
select id,name from t4 where id
select id,name from t4 where name='lili';
(and or)语法:select 字段,字段2 from 表名 where 条件 and/or where 条件;
select name,sex from t5 where post='hr' and office=502;
(4)统计记录数量:
select count(*) from t4;
(5)统计字段得到数量:
select count(id) from t4;
(6)分组查询:
group by
select count(name),post from t5 group by post;
(7)按关键字查询:
select name,post from t5 where job_descriptio;
(8)按 limit 限制条件:
select * from t5 limit 2; (只显示前2行)
(9)排序查询
order by
从小到大排序:select name,office from t5 order by id;
从大到小排序:select name,office from t5 order by id desc;