MySQL基本操作
增
- 创建一个新的数据库 create database [if not exists] dbname;
- 创建一个新的数据库并指定字符编码:
- create database if not exists dbname default character set utf8;
- 创建数据表:
create table [if not exists] tabname(
列名 数据类型和长度 列属性,
列名 数据类型和长度 列属性,
列名 数据类型和长度 列属性,
列名 数据类型和长度 列属性
);
- 插入记录 insert into tabname value(数据列表);
- 指定字段插入记录 insert into tabname(字段名) value(数据列表);
- 在表中添加新的字段 alter table tabname add 字段名 字段定义 [first|after 列名];
- 添加主键 alter table tabname add primary key (主键名);
删
- 删除数据库 drop database [if exists] dbname;
- 删除一张表 drop table [if exists] tabname;
- 删除一个字段 alter table tabname drop 字段名;
- 删除所有记录 delete from tabname;
- 删除符合条件的记录 delete from tabname where 字段名 = 字段值;
- 删除主键 alter table tabname drop primary key;
改
- 修改数据库默认的编码 alter database dbname default character set utf8 collate utf8_bin;
- 修改表的字段的数据类型 alter table tabname modify 字段名 字段定义;
- 修改表的字段名 alter table tabname change 旧字段名 新字段名 新字段定义;
- 修改记录中字段的值 update tabname set 字段名 = 新值 where 字段名 = 匹配值;
- 修改表名 alter table tabname rename [to] 新表名;
查
- 选择数据库 use dbname;
- 显示所有数据库 show databases;
- 查看数据库的创建信息 show create database dbname;
- 查看表的定义 show create table tabname;
- 显示数据库中的所有表 show [full] tables [{from|in} dbname];
- 查看表的创建信息 desc tabname;
- 查询正在使用的数据库 select databace();
- 查询记录 select * from tabname;
数据类型
数据类型 | 标识符 | 大小 | 范围(有符号/无符号) |
---|
微整数 | tinyint | 1B | (-128,127/0,255) |
小整数 | smallint | 2B | (-32768,32767/0,65535) |
中整数 | mediumint | 3B | (±8388608/16777215) |
整数 | int | 4B | (±2147483648) |
大整数 | bigint | 8B | (±9223372036854775808) |
单精度 | float | 4B | (IEEE754) |
双精度 | double | 8B | (IEEE754) |
定点数 | decimal | - | (看情况) |
日期 | date | 3B | (1000-01-01/9999-12-31) |
时间 | time | 3B | (-838:59:59/838:59:59) |
日期时间 | datetime | 8B | (9999-12-31 23:59:59) |
时间戳 | timestamp | 4B | (2038-1-19 11:14:07) |
字符串 | char(255) | 255B | (0-255) |
长字符串 | varchar | 65KB | (0-65536) |
短文本 | tinytext | 255B | (0-255) |
文本 | text | 65KB | (0-65536) |
中文本 | mediumtext | 16MB | (0-16777215) |
长文本 | longtext | 4GB | ( 0-4294967295) |
表约束
约束类型 | 描述 | 约束对象 |
---|
not null | 列的值不能为空 | 列 |
auto_increment | 列的时自动增加(只能和主键或唯一配合使用) | 列 |
default | 设置列的默认值 | 列 |
primary key | 设置为主键,键不能重复,不能为空 | 行 |
unique | 设置为唯一键,该列不能重复 | 行 |
foreign key | 设置为外键 | 表 |
comment | 字段描述 | - |
添加约束
- 添加自增长 alter table tabname modify 字段名 字段定义 auto_incremant;
- 添加非空约束 alter table tabname modify 字段名 字段定义 not null;
- 添加唯一约束 alter table tabname add key [constraint 约束名] unique(字段名);
- 添加默认值 alter table tabname change column 字段名 字段定义 default 默认值;
删除约束
- 删除非空约束 alter table tabname modify 字段名 字段定义 null;
- 删除默认值 alter table tabname alter 字段名 drop default;
- 删除唯一约束 alter table tabname drop key 约束名;(约束名默认为字段名)