SQL语句:html
数据库mysql
建立:createdatabase [if not exists] db_name[character set ‘gbk’] [collate‘gbk_chinese_ci’]sql
查看字符集 show characterset;数据库
查看字符集排序规则 showcollation;ide
cd /mydata/data cat db.opt 里面保存了数据的字符集和排序规则[配置文件/etc/my.cnf能够查看该目录位置]工具
字符集扩展spa
字符集基础3d
Mysql字符集和字符集排序规则(有时候使用mysql工具链接mysql后会中文乱码,就是字符集的问题htm
二者关系:一个字符集能够有多个排序规则,有一个默认的排序方式。blog
例子:
show character like '%gbk%';
show collation like '%gbk%';
排序方式的命名规则为:字符集名字_语言_后缀
2.修改默认字符集
修改
Help alter database
通常就是修改数据库的字符集和排序规则
删除
Drop database db_name;
修改数据库名字呢?
停掉数据库,去数据库文件目录重命名而后重启数据库就能够 不推荐 通常是不给数据库重命名的要事先命好名字
表
建立 一个表只有一个主键 但能够有多个惟一键
直接定义一张空表 create table [if not exists] tb_name (col_namecol_definition)idi
例:create table tb1 (id int unsigned not null auto_increment primary key,name char(20) not null,agetinyint not null);
主键能够单独定义create table tb1 (id int unsigned not null auto_increment ,namechar(20) not null,age tinyint not null,primary key (id));
或primary (id,name)把id name组合起来作主键
或 unique key (name) 把name做惟一键 或index key(age)把age字段做为索引
任何一个自动增加的都必须为主键
说明:键也称做约束,可用做索引,属于特殊索引(有特殊限定),存储起来是B+Tree结构,
Create index 建立索引 索引分为两种 BTREE 和HASH两种
Show indexes from tb_name 显示表上的索引
例子 courses课程名称
Create table courses(CID tinyint unsigned not null auto_increment primarykey,couse varchar(50) not null);
默认建立引擎为Innodb show table statuslike ‘courses’\G;
Drop table courses;
指定引擎Create table courses(CID tinyint unsigned not null auto_increment primary key,couse varchar(50)not null) ENGINE=MyIsam;
第二种建立表利用查询到的直接建立表
Desc courses;
Desc testcourses;
不少咱们利用查询出来的数据建立表不少字段定义的格式不见了,要注意这一点
第三种以其它表为模板建立空表
Create table test Like courses;
Desc test;显示表结构
若是咱们既要保存格式又要把查询的数据保存进去,后面讲到insert再说
从其余表中查询出数据,并以之建立新表
以其余表为模板建立一个空表
修改表定义
Alter table
添加 删除 修改字段
添加 删除 修改索引
改表名
修改表属性
如今咱们为test添加一个惟一键索引
alter table test add unique key (couse);
show indexes from test;
改course字段名称 用change modify均可以
alter table test change couse course varchar(50) not null;
desc test
新增一个开课日期字段
alte table test add starttime date default '2013-08-25';
Startime改成startdate
alter table test change starttime startdate date ;
给表更名 不要随便改
alter table test rename to test2;
删除表
添加个外键约束
有时候添加外键可能添加不上,
引擎是否为Innodb
表值清空
上面2步就能够建立外键了,建立完后如今course添加数据,而后根据course的cid外键在
student添加数据
先把上面的删除
References参考
注意外键约束只能用在存储事务的存储引擎上,在INNODB引擎能够 myisam不能够
失败 建立新表的时候没法改表引擎,比较痛苦
能够直接修改表引擎
Show table status\G;
字段类型保持一致
此时学一个不存在的课就不能添加了,这就是引用性约束,另外一个表中没有是不容许使用的
若是我把3删了把有选修的课删了
此时不让删有别的引用了
能够强行删除级联
索引
索引不能被修改 只能建立 删除
Create index index_name on tb_name (col,…);
视图
DML