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;

数据类型

数据类型标识符大小范围(有符号/无符号)
微整数tinyint1B(-128,127/0,255)
小整数smallint2B(-32768,32767/0,65535)
中整数mediumint3B(±8388608/16777215)
整数int4B(±2147483648)
大整数bigint8B(±9223372036854775808)
单精度float4B(IEEE754)
双精度double8B(IEEE754)
定点数decimal-(看情况)
日期date3B(1000-01-01/9999-12-31)
时间time3B(-838:59:59/838:59:59)
日期时间datetime8B(9999-12-31 23:59:59)
时间戳timestamp4B(2038-1-19 11:14:07)
字符串char(255)255B(0-255)
长字符串varchar65KB(0-65536)
短文本tinytext255B(0-255)
文本text65KB(0-65536)
中文本mediumtext16MB(0-16777215)
长文本longtext4GB( 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 约束名;(约束名默认为字段名)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值