01.创建表的样例
1.1 直接创建表:
CREATE TABLE
[IF NOT EXISTS] tb_name -- 不存在才创建,存在就跳过
(column_name1 data_type1 -- 列名和类型必选
[ PRIMARY KEY -- 可选的约束,主键
| FOREIGN KEY -- 外键,引用其他表的键值
| AUTO_INCREMENT -- 自增ID
| COMMENT comment -- 列注释(评论)
| DEFAULT default_value -- 默认值
| UNIQUE -- 唯一性约束,不允许两条记录该列值相同
| NOT NULL -- 该列非空
], ...
) [CHARACTER SET charset] -- 字符集编码
[COLLATE collate_value] -- 列排序和比较时的规则(是否区分大小写等)
1.2 从另一张表复制表结构创建表:
CREATE TABLE tb_name LIKE tb_name_old
1.3 从另一张表的查询结果创建表:
CREATE TABLE tb_name AS SELECT * FROM tb_name_old WHERE options
CREATE table if not exists user_info_vip (
id int primary key auto_increment comment '自增ID',
uid int unique not null comment '用户ID',
nick_name varchar(64) comment '昵称',
achievement int default 0 comment '成就值',
`level` int comment '用户等级',
job varchar(32) comment '职业方向',
register_time datetime default CURRENT_TIMESTAMP comment '注册时间'
) character set utf8 COLLATE utf8_general_ci ;
describe user_info_vip ;
输出结果:
02.修改表的信息
ALTER TABLE user_info ADD f1 varchar(15) AFTER f2;
ALTER TABLE user_info CHANGE f1 f2 varchar(10);
ALTER TABLE user_info CHANGE COLUMN f1 f1 int DEFAULT value;
2.1.在某个字段后面插入一个新的字段
ALTER table user_info_vip add school varchar(15) after `level`;
describe user_info_vip ;
输出结果:
2.2.更新表的列名,改变字段长度
ALTER table user_info_vip change job profession varchar(10);
describe user_info_vip ;
输出结果:
2.3.设置默认值
alter table user_info_vip change column achievement achievement int default 0;
describe user_info_vip ;
也可以使用:ALTER TABLE user_info MODIFY achievement INT(11
) DEFAULT 0
;这种方式进行修改
输出结果:
03.删除已经存在的多个表
3.1.创建多个表进行模拟
drop table if EXISTS exam_record;
CREATE TABLE IF NOT EXISTS exam_record (
id int PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID',
uid int NOT NULL COMMENT '用户ID',
exam_id int NOT NULL COMMENT '试卷ID',
start_time datetime NOT NULL COMMENT '开始时间',
submit_time datetime COMMENT '提交时间',
score tinyint COMMENT '得分'
)CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS exam_record_2010 (LIKE exam_record);
CREATE TABLE IF NOT EXISTS exam_record_2012 (LIKE exam_record);
CREATE TABLE IF NOT EXISTS exam_record_2013 (LIKE exam_record);
CREATE TABLE IF NOT EXISTS exam_record_2014 (LIKE exam_record);
CREATE TABLE IF NOT EXISTS exam_record_2015 (LIKE exam_record);
3.2.匹配查询表有那些
SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'exam_record_201_' ;
输出结果:
3.3.删除的多个表(存在的情况下)
drop table if exists exam_record_2011, exam_record_2012,exam_record_2013,exam_record_2014;
并使用通配符匹配查询剩下的所有表
SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'exam_record_201_' ;
输出结果:
并使用通配符匹配查询剩下的所有表
SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME LIKE 'exam_record_201_' ;
输出结果: