MYSQL——表操作

一、表操作(表与字段密不可分,字段即表中的列)

1.新增数据表:

 --create table 【if not exists】表名(字段名字 数据类型, 字段名字 数据类型, 最后一行不需要逗号)【表选项】; 

注解:(1) if not exists: 如果表名不存在,就创建,否则不执行创建代码;检查功能

      (2) 表选项:控制表 表现,包含以下3个方面

               字符集:charset/character set 具体字符集 --  保证表中数据存储的字符集

               校对集:collate 具体校对集 ;

               存储引擎:engine 具体的存储引擎(innodb和 myisam)

 1 --例子:
 2 create table if not exists student (name varchar(10), gender  varchar(10), number    
 3  varchar(10), age  int) charset utf8;
 4 --上述结果报错,因为没有指定数据库,任何一个表的设计都必须指定数据库
 5 --方案1: create table 数据库名.表名(  ) ; 表示将当前数据表创建到指定数据库下,建的表自动归属到某个指定的数据库,
 6 --eg1:
 7 create table if not exists mydatabase.student (name varchar(10), gender  varchar(10), number    
 8  varchar(10), age  int) charset utf8;--显示的将student 表放到mydatabase 库下
 9 
10 --方案2:进入数据库环境: use 数据库名字(可以无分号)
11 --eg2:
12 use mydatabase;
13 create table class (name varchar(10), room varchar(10) ) charset utf8;

 2.查看数据表

   数据库能查看的方式表都可以查看

扫描二维码关注公众号,回复: 1470677 查看本文章
 1 --(1) 查看所有表:
 2 show tables;
 3 --(2)查看部分表:模糊匹配:
 4 --show tables like 'pattern';
 5 --例子1:查看以s结尾的表:
 6 show tables like '%s';
 7 --(3)查看表的创建语句:
 8 --show create table 表名;
 9 show create table student\g  --\g==;
10 show create table student\G  --将查到的结构旋转90度变成纵向
11 --(4)查看表结构:查看表中的字段信息
12 --Desc/describle/show columns from 表名;
13 --例子:
14 Desc class;
15 describe class;
16 show columns from class;

 3.修改数据表

表本身存在,还包含字段;表的修改分为两个部分,分别为修改表本身和修改字段

(1)修改表本身

        表本身可以修改:表名和表选项

1 --(1)修改表名: rename table 旧表名 to 新表名;
2 --eg1:
3 rename table student to my_student;
4 
5 --(2) 修改表选项:字符集、校对集和存储引擎   alter table 表名 表选项【=】值;
6 --eg2:
7 alter table my_student charset=GBK;

(2)修改字段: 

字段的操作包括:新增、修改、重命名、删除。

  (a)新增字段:Alter table 表名 add【column】字段名 数据类型 【列属性】【位置】;

           位置:字段名可以存放表中的任意位置,First:第一个位置,  After:在哪个字段之后:after 字段名;默认的是在最后一个字段之后

1 --例子:给学生表增加ID到第一个位置
2 Alter table my_student add column id int first;

  (b) 修改字段: Alter table 表名 modify 字段名 数据类型 【属性】【位置】;

1 --例子:将学生表中的number 学号字段变成固定字段,且放到第2位(id)之后
2 Alter table my_student modify number char(10) after id;

  (c)重命名字段;After table 表名 change 旧字段名 新字段名 数据类型 【属性【位置】;

1 --例子:修改学生表中的gender字段名为sex;
2 Alter table my_student change gender sex varchar(10);

 (d)删除字段: Alter table 表名 drop 字段名;

1 --例子:删除学生表中的的age
2 Alter table my_student drop age;

 注:如果表中已经存在数据,删除字段会清空该字段的所有数据(删除不可逆)。

  4.删除数据表

   drop table 表名1,表名2,....;    可以一次性删除多张表

1 --例子:
2 drop table class;

注:删除有危险,操作需谨慎!!!

猜你喜欢

转载自www.cnblogs.com/xwxs/p/9135613.html