MySQL 命令基本操作 (持续更新)

MySQL基本操作

  1. 创建一个新的数据库 create database [if not exists] dbname;
  2. 创建一个新的数据库并指定字符编码:
    • create database if not exists dbname default character set utf8;
  3. 创建数据表:
create table [if not exists] tabname(
    列名   数据类型和长度  列属性,
    列名   数据类型和长度  列属性,
    列名   数据类型和长度  列属性,
    列名   数据类型和长度  列属性
);
  1. 插入记录 insert into tabname value(数据列表);
  2. 指定字段插入记录 insert into tabname(字段名) value(数据列表);
  3. 在表中添加新的字段 alter table tabname add 字段名 字段定义 [first|after 列名];
  4. 添加主键 alter table tabname add primary key (主键名);

  1. 删除数据库 drop database [if exists] dbname;
  2. 删除一张表 drop table [if exists] tabname;
  3. 删除一个字段 alter table tabname drop 字段名;
  4. 删除所有记录 delete from tabname;
  5. 删除符合条件的记录 delete from tabname where 字段名 = 字段值;
  6. 删除主键 alter table tabname drop primary key;

  1. 修改数据库默认的编码 alter database dbname default character set utf8 collate utf8_bin;
  2. 修改表的字段的数据类型 alter table tabname modify 字段名 字段定义;
  3. 修改表的字段名 alter table tabname change 旧字段名 新字段名 新字段定义;
  4. 修改记录中字段的值 update tabname set 字段名 = 新值 where 字段名 = 匹配值;
  5. 修改表名 alter table tabname rename [to] 新表名;

  1. 选择数据库 use dbname;
  2. 显示所有数据库 show databases;
  3. 查看数据库的创建信息 show create database dbname;
  4. 查看表的定义 show create table tabname;
  5. 显示数据库中的所有表 show [full] tables [{from|in} dbname];
  6. 查看表的创建信息 desc tabname;
  7. 查询正在使用的数据库 select databace();
  8. 查询记录 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 字段描述 -

添加约束

  1. 添加自增长 alter table tabname modify 字段名 字段定义 auto_incremant;
  2. 添加非空约束 alter table tabname modify 字段名 字段定义 not null;
  3. 添加唯一约束 alter table tabname add key [constraint 约束名] unique(字段名);
  4. 添加默认值 alter table tabname change column 字段名 字段定义 default 默认值;

删除约束

  1. 删除非空约束 alter table tabname modify 字段名 字段定义 null;
  2. 删除默认值 alter table tabname alter 字段名 drop default;
  3. 删除唯一约束 alter table tabname drop key 约束名;(约束名默认为字段名)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章