数据库表的操作主要包括修改表名、查看表结构、添加字段、删除字段、修改字段类型、修改字段名、给表设置主键、设置自增长字段、删除表、清空表。下面会一一举例。
创建表
#最简单的方式:
mysql> create table stu(
-> id int not null primary key,
-> name varchar(20) default null
-> );
Query OK, 0 rows affected (0.01 sec)
修改表名 rename
# 修改stu表名称为student
mysql> alter table stu rename student;
Query OK, 0 rows affected (0.01 sec)
mysql> show tables;
+-----------------+
| Tables_in_hello |
+-----------------+
| article |
| student |
+————————+
查看表结构 desc
mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
添加字段 add
给student表添加班级(class)字段
mysql> alter table student add class varchar(20);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
删除字段 drop
# 删除student表的班级(class)字段
mysql> alter table student drop class;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
修改字段类型 modify
# 修改student表的name类型为char(18)
mysql> alter table student modify name char(18);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
给表设置主键 modify
mysql> alter table student modify id int(11) primary key;
修改字段名 change
# 修改student 表的name varchar(20)字段为name char(10)
mysql> alter table student change name name char(10);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
复制表
# 复制stu表结构+记录
mysql> create table new_stu select * from stu;
Query OK, 7 rows affected (0.01 sec)
Records: 7 Duplicates: 0 Warnings: 0
# 只复制表结构
mysql> create table new_stu2 select * from stu where 1=2;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
删除表
mysql> drop table new_student;
Query OK, 0 rows affected (0.01 sec)
设置自增长字段
mysql> alter table stu change id id int AUTO_INCREMENT;
Query OK, 7 rows affected (0.02 sec)
Records: 7 Duplicates: 0 Warnings: 0
清空表
注意:
清空表不要使用delete,delete清空的表不会重置auto_increment,下次插入的记录的自增id不是从默认的自增id开始的。
通常delete 是和where语句配合使用删除固定条件的记录的
清空表需要使用truncate,truncate清空的表会重置自增起始偏移量
mysql> delete from stu;
mysql> show create table stu;
CREATE TABLE `stu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
清空表使用truncate,truncate清空的表会重置自增起始偏移量,验证如下:
mysql> truncate table stu;
Query OK, 0 rows affected (0.01 sec)
mysql> show create table stu;
CREATE TABLE `stu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
mysql> insert into stu(name) value("jack");
Query OK, 1 row affected (0.01 sec)
mysql> select * from stu;
+----+------+
| id | name |
+----+------+
| 1 | jack |
+----+------+
1 row in set (0.00 sec)
网友评论