一、创建表create table 表名 (
字段名1 类型1,
....
字段名n 类型n
);
例:创建个student表,设,所有字段不能为空。CREATE TABLE student (
id int(4) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name char(20) NOT NULL,
age tinyint(2) NOT NULL DEFAULT ‘0‘,
dept varchar(16) DEFAULT NULL
);
Query OK, 0 rows affected (0.09 sec)约束说明
PRIMARY KEY标识该属性为该表的主键,可以唯一的标识对应的元组
FOREIGN KEY标识该属性为该表的外键,是与之联系某表的主键
NOT NULL标识该属性不能为空
UNIQUE标识该属性的值是唯一的
AUTO_INCREMENT标识该属性的值是自动增加,这是MySQL的SQL语句的特色
DEFAULT为该属性设置默认值
二、删除表
drop table 表名;
三、更改表
1.修改表名
alter table 旧表名 rename 新表名;>alter table student rename student1;
Query OK, 0 rows affected (0.07 sec)
2.修改字段类型
alter table 表名 modify 属性名 数据类型;>alter table student modify name varchar(20);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
3.修改字段名
alter table 表名 change 旧属性名 新属性名 新数据类型;>alter table student change name stu_name char(20);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
4.添加字段名
alter table 表名 add 属性1 数据类型[约束条件] [first | after 属性2];
--first 新增字段设置为表的第一个字段
--after 放在属性2 后面,(属性2 是已有字段)>alter table student1 add teacher varchar(20) after stu_name;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
5.删除字段
alter table 表名 drop 属性名;>alter table student1 drop teachar;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
6.更改存储引擎
alter table 表名 engine = 存储引擎名;>alter table student1 engine = MYISAM;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
7.添加主键
alter table 表名 change id id int primary key auto_increment;l> alter table student change id id int primary key auto_increment;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
四、查询表
1.查看表结构
desc 表名;> desc student
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(4) | NO | | NULL | |
| name | char(20) | NO | | NULL | |
| age | tinyint(2) | NO | | 0 | |
| dept | varchar(16) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)>show columns from 表名;(不常用)
2.查看已建表的语句show create table 表名\G> show create table student \G
*************************** 1. row ***************************
Table: student
Create Table: CREATE TABLE `student` (
`id` int(4) NOT NULL,
`name` char(20) NOT NULL,
`age` tinyint(2) NOT NULL DEFAULT ‘0‘,
`dept` varchar(16) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
原文:http://dahui09.blog.51cto.com/10693267/1705253