1.创建表
CREATE TABLE table_name (
field1 datatype,
field2 datatype,
field3 datatype
) character set 字符集 collate 校验规则 engine 存储引擎;
fields:表示列名
datatype:数据名
character set:表示字符集
collate :校验规则
engine:存储引擎
字符集 (charset) 决定存什么字节;校验规则 collation 决定怎么比较、排序字符。
MySQL 是插件式架构,存储引擎是 MySQL 负责数据怎么存储、读取、索引实现的底层模块。 SQL 解析、优化器是上层;真正落地读写磁盘、事务、锁、索引,由存储引擎完成。
mysql> create table users(
-> id int,
-> name varchar(20) comment '用户名',
-> password char(32) comment '密码',
-> birthday date comment '生日'
-> )character set utf8 engine MyISAM;
2.查看表结构
desc 表名;
例子:
mysql> desc users;
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
| password | char(32) | YES | | NULL | |
| birthday | date | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
3.修改表
(1)添加列
ALTER TABLE tablename ADD (column datatype DEFAULT expr,column datatype...);
mysql> alter table users add ( weight int);Query OK, 0 rows affected (0.05 sec)
mysql> alter table users add age int after birthday;Query OK, 0 rows affected (0.06 sec)
Records: 0 Duplicates: 0 Warnings: 0
(2)更改列
ALTER TABLE tablename MODIfy (column datatype DEFAULT expr,column datatype...);
mysql> alter table users modify weight float;
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
(3)删除列
ALTER TABLE tablename DROP (column);
mysql> alter table users drop weight;
Query OK, 0 rows affected (0.06 sec)
Records: 0 Duplicates: 0 Warnings: 0
(4)修改表名
mysql> alter table users rename to students;
(5)修改列名
mysql> alter table students change name xingming varchar(60);
Query OK, 0 rows affected (0.11 sec)
Records: 0 Duplicates: 0 Warnings: 0
(6) 删除表
mysql> drop table students;
Query OK, 0 rows affected (0.03 sec)