在mysql中表的创建有三种方式:
1、直接定义一张空表;
2、从其它表中查询出数据,并以之创建新表;
3、以其它表为模板创建一个空表;
<code> CREATE TABLE [IF NOT EXISTS] tb_name (col_name col_defination, constraint ) </code>
创建表的三种方式:
<code> mysql> create table course(cid tinyint unsigned not null auto_increment primary key,course varchar(50) not null) engine=MyISAM; #直接定义一张表,并设置默认引擎 mysql> create table testcourse select * from course where cid <=2; #从一张表中创建一个表,字段类型会变 mysql> create table test like course; #以其他表为模板创件,默认字段类型不会变 </code>
例:
<code> CREATE TABLE tb1 (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, Name CHAR(20) NOT NULL, Age TINYINT NOT NULL) ENGINE [=] engine_name CREATE TABLE tb2 (id INT UNSIGNED NOT NULL AUTO_INCREMENT, Name CHAR(20) NOT NULL, Age TINYINT NOT NULL, PRIMARY KEY(id),UNIQUE KEY(name),INDEX(age)) </code>
创建时使用单字段:
<code> PRIMARY KEY UNIQUE KEY </code>
多字段的使用方法:
<code> PRAMARY KEY (col,...) UNIQUE KEY (col,...) INDEX (col,...) </code>
修改表定义:
<code> ALTER TABLE 添加、删除、修改字段 添加、删除、修改索引 改表名 修改表属性 </code>
删除表:
<code> DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name </code>
注意,以下两种用法的区别:
modify:修改表中的数据类型
change:改变表中列的名字
<code> mysql> alter table test add unique (course); #给一个表插入一个唯一键 mysql> alter table test change course courses varchar(50) not null; #修改字段的名称 mysql> alter table test change starttime startdate date default '2015-05-28';#修改表的列的名字 mysql> rename table testcourses to test; #重命名一张表 mysql> alter table test rename to testcourses; #重命名一张表 mysql> alter table student modify cid tinyint unsigned not null ; #修改表字段的类型 mysql> alter table student add foreign key foreign_cid(CID) references course(cid);#添加外键 mysql> delete from course where cid=3; #删除一张表 mysql> alter table course engine=InnoDB; #修改默认引擎 </code>
注意:
MyISAM不支持外键,InnoDB支持外键,外键引擎只能用在支持事务的存储引擎上。
索引对查询的速度有着至关重要的影响,理解索引也是进行数据库性能调优的起点。键也称作约束,可用作索引,属于特殊索引(有特殊限定)。
索引创建:
<code> CREATE INDEX index_name ON tb_name (col,...); col_name [(length)] [ASC | DESC] mysql> create index name_on_student on student(name); #创建一个索引 mysql> create index name_on_student on student(name(5) desc); #创建索引在前五个字符上按降序排序。 mysql> show indexes from course; #查看索引 </code>