MySQL中对表的基本操作,更改表结构
MySQL数据库中对表的基本操作
在对表进行操作之前需要引用一个数据库,即选中一个数据库进行操作。
use student; # 使用库,指定要操作的库
执行完后显示Database changed -> 即代表已选中此库
show tables; # 查看当前已选中的库中的表
创建表
create table student( id int, name varchar(30), # varchar 字符串 age int # 最后一个不用加逗号 ); 注:MySQL语句中忽略空格,语句可以全输在同一行,也可以分成多行,它们的作用相同。为增加可读性以便阅读与编辑,建议采用缩进格式。
创建一个名为student的表,其中包括字段id(int类型),name(varchar类型且宽度为30),age(int类型)
在创建新表时,指定的表名必须不存在,否则将出错。
创建表示例:
create table if not exists teacher( id int auto_increment primary key comment 主键id, # auro_increment -> 自动增长,即id按int类型自动增长,自增必须主是主键,但是主键不一定是自增 # comment 注释 name varchar (30) not null comment 名字, # not null 即不能为空 phomeNum varchar(20) comment 电话号, address varchar(100) default 暂时未知 comment 住址 # default 没填时的默认值 )engine = innodb; # engine 数据库引擎,现在使用最多的是innodb,最好写全,若非要用关键关键字,要用反引号引起来(没啥用,不要使用关键字)
查看表如何创建
desc teacher; # 查看teacher表是如何创建的,表的SQL语句
查看表结构
desc teacher; # 列出teacher表的结构 show columns from teacher; describe teacher; # 三种均为查看表结构
删除表
drop table stu;
drop table if exists s,stu,000,j; # 即,若存在,删除,删除多个时用逗号隔开 # 不能撤销,永久删除
更新表的结构
更新表定义时,使用alter table语句。
理想状态下,当表中存储数据之后,该表的结构就不应该被改变。 在表的设计过程中需要花费大量时间考虑,以便后期不对该表进行大的改动。 在使用alter table 时要极为小心,应在进行改动前做一个完整的数据和模式的备份。
添加字段(add)
alter table student add phone varchar(20); # 在student表中添加字段phone,类型varchar,宽度20
指定位置添加字段:
alter table student add gender varchar(1) after name; # 放在最后
alter table student add gender varchar(1) first; # 放在最前
删除字段(drop)
alter table student drop address; alter table student drop column address; # 删除student表中字段address
修改字段(change)
alter table student change phone tel int(11); # 将student表中的字段phone改为tel,类型为int(11)
修改字段类型,不改名(modify)
alter table student modify tel varchar(13); # 将student表中的tel字段改为varchar(11)
只改表中字段名(rename)
alter table student rename to students; # 将表student改名为students
重命名表
rename table student to students; # 将表student重命名为students # 若要对多个表重命名 rename table student to students, teacher to teachers, a to b;
外键的定义
定义外键是alter table语句的一种常见用途
定义外键的代码如下:
alter table orderitems add constraint fk_orderitems_orders foreign key (order_num) references orders(order_num);