[TOC]
一、数据表的操作
1.1 查看当前数据库中所有表
-- 查看当前数据库中所有表
show tables;
1.2 查看数据表结构
-- 查看数据表表结构
desc 数据表的名字;
1.3 创建表
-- 创建表
-- auto_increment表示自动增长
-- not null 表示不能为空
-- primary key 表示主键
-- default 默认值
-- create table 数据表名字 (字段 类型 约束[, 字段 类型 约束]);
create table xxxxx(id int, name varchar(30));
create table yyyyy(id int primary key not null auto_increment, name varchar(30));
create table zzzzz(
id int primary key not null auto_increment,
name varchar(30)
);
1.4 查看表的创建语句(重点)
-- show create table 表名;
show create table students;
| students | CREATE TABLE `students` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT '',
`age` tinyint(3) unsigned DEFAULT '0',
`height` decimal(5,2) DEFAULT NULL,
`gender` enum('男','女','中性','保密') DEFAULT '保密',
`cls_id` int(10) unsigned DEFAULT '0',
`is_delete` bit(1) DEFAULT b'0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1.4 示例
先使用数据库,之后创建表
1.4.1 创建表
-- 创建students表(id、name、age、high、gender、cls_id)
create table students(
id int unsigned not null auto_increment primary key,
name varchar(30),
age tinyint unsigned default 0,
high decimal(5,2),
gender enum("男", "女", "中性", "保密") default "保密",
cls_id int unsigned
);
1.4.2 插入数据(重点)
-- 按照创建表结构的顺序插入数据
insert into students values(0, "老王", 18, 188.88, "男", 0);
1.4.3 查看插入的数据
-- 查看插入的数据
select * from students;
二、修改表结构(alter)
2.1 修改表-添加字段
-- alter table 表名 add 列名 类型;
alter table students add birthday datetime;
2.2 修改表-修改字段:不重命名版(改类型和约束)
-- alter table 表名 modify 列名 类型及约束;
alter table students modify birthday date;
2.3 修改表-修改字段:重命名版(改列名)
-- alter table 表名 change 原名 新名 类型及约束;
alter table students change birthday birth date default "2000-01-01";
2.4 修改表-删除字段(删除列名)
-- alter table 表名 drop 列名;
alter table students drop high;
2.5 删除表
-- drop database 数据库;
-- drop table 表名;
drop table xxxxx;
drop table students;
三、总结
-- 创建students表(id、name、age、high、gender、cls_id)
create table students(
id int unsigned not null auto_increment primary key,
name varchar(30),
age tinyint unsigned default 0,
high decimal(5,2),
gender enum("男", "女", "中性", "保密") default "保密",
cls_id int unsigned
);
insert into students values(0, "老王", 18, 188.88, "男", 0);
select * from students;
-- 创建classes表(id、name)
create table classes(
id int unsigned not null auto_increment primary key,
name varchar(30)
);
insert into classes values(0, "python04大神");
select * from classes;
-- 查看表的创建语句
-- show create table 表名字;
show create table students;
-- 修改表-添加字段
-- alter table 表名 add 列名 类型;
alter table students add birthday datetime;
-- 修改表-修改字段:不重命名版
-- alter table 表名 modify 列名 类型及约束;
alter table students modify birthday date;
-- 修改表-修改字段:重命名版
-- alter table 表名 change 原名 新名 类型及约束;
alter table students change birthday birth date default "2000-01-01";
-- 修改表-删除字段
-- alter table 表名 drop 列名;
alter table students drop high;
-- 删除表
-- drop table 表名;
-- drop database 数据库;
-- drop table 数据表;
drop table xxxxx;