MySQL表操作
-
1. 存储引擎
- MySQL中的数据用各种不同的技术存储在文件(或者内存)中;这些技术中的每一种技术都使用不同的存储机制、索引技巧、锁定水平并且最终提供广泛的不同的功能和能力。通过选择不同的技术,你能够获得额外的速度或者功能,从而改善你的应用的整体功能。
- 存储引擎即表类型,mysql根据不同的表类型会有不同的处理机制
-
2. 表介绍
- 表相当于文件,表中的一条记录就相当于文件的一行内容,不同的是,表中的一条记录有对应的标题,称为表的字段
- 某一行内容被称为:某一条记录
- 某一列名被称为:某一个字段
-
3. 创建表 create table
-
语法#语法: create table 表名( 字段名1 类型[(宽度) 约束条件], 字段名2 类型[(宽度) 约束条件], 字段名3 类型[(宽度) 约束条件] ); #注意: 1. 在同一张表中,字段名是不能相同 2. 宽度和约束条件可选 3. 字段名和类型是必须的
create table t1(id int,name char(10)) default charset=utf8; create table t1(id int,name char(10))engine=innodb default charset=utf8; create table t3(id int auto_increment primary key,name char(10))engine=innodb default charset=utf8; #推荐使用第三种 #五大约束:主键、外键、非空、默认、唯一 create table t1( 列名 类型 primary key, -- 主键 列名 类型 constraint `FK_ID` foreign key (`user_id`) references `tb_user` (`id`) , -- 外键(fk_id是外键的名称) 列名 类型 not null, -- 非空 列名 类型 not null defalut 2, 列名 类型 not null,primary key, auto_increment , -- 非空主键自增长 id int, name char(10) )engine=innodb default charset=utf8; # innodb 支持事务,原子性操作。即操作中断后不会丢失数据,会返回中断前数据。 # myisam mysql默认myisam,数据会丢失。所以一般设置模式为innodb # charset 指定字符编码 auto_increment: 表示:自增1。写入内容为空时,默认从1,2,3...往下填充写入表格中。 primary key: 表示主键约束(不能重复且不能为空); 加速查找 not null: 不能为空 defalut: 后面跟默认值
-
外键示例外键,一个特殊的索引,只能是指定内容 creat table color( nid int not null primary key, name char(16) not null ) create table fruit( nid int not null primary key, smt char(32) null , color_id int not null, constraint fk_cc foreign key (color_id) references color(nid) )
主键补充主键,一种特殊的唯一索引,不允许有空值,如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一。 create table tb1( nid int not null auto_increment primary key, #主键为nid num int null ) 或 create table tb1( nid int not null, num int not null, primary key(nid,num) #主键为nid和num )
自增补充自增,如果为某列设置自增列,插入数据时无需设置此列,默认将自增(表中只能有一个自增列) create table tb1( nid int not null auto_increment primary key, num int null ) 或 create table tb1( nid int not null auto_increment, num int null, index(nid) ) 注意:1、对于自增列,必须是索引(含主键)。 2、对于自增可以设置步长和起始值 基于会话级别: show session variables like 'auto_inc%'; 查看全局变量 set session auto_increment_increment=2; 设置会话步长 set session auto_increment_offset=10; 默认步长为1,设置初始值为10 基于全局级别: show global variables like 'auto_inc%'; 查看全局变量 set global auto_increment_increment=2; 设置会话步长 set global auto_increment_offset=10;
- 查看表结构:desc tablename
MySQL> describe t1; #查看表结构,可简写为desc 表名 +-------+-----------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-----------------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | varchar(50) | YES | | NULL | | | sex | enum('male','female') | YES | | NULL | | | age | int(3) | YES | | NULL | | +-------+-----------------------+------+-----+---------+-------+ MySQL> show create table t1\G; #查看表详细结构(创建表语句),可加\G
-
-
修改表 alter table tablename

浙公网安备 33010602011771号