MySQL 基础入门笔记,涵盖 DDL 数据定义、DML 数据操纵与 DQL 数据查询三大核心板块。
一、连接 MySQL
安装好 MySQL 后,打开命令行终端,输入以下命令连接数据库:
mysql-u root-p-u指定用户名(root 是超级管理员)-p表示需要输入密码
连接成功后会出现mysql>提示符。退出输入:
exit;二、数据库与表的基本操作(DDL)
DDL(Data Definition Language)用于定义和管理数据库结构:库、表、字段。
2.1 数据库操作
| 操作 | SQL 语句 | 说明 |
|---|---|---|
| 查看所有库 | show databases; | 列出当前 MySQL 中所有数据库 |
| 进入库 | use 数据库名; | 切换到指定数据库 |
| 创建库 | create database 数据库名; | 新建一个数据库 |
| 删除库 | drop database 数据库名; | 危险操作,删除整个库 |
2.2 表操作
| 操作 | SQL 语句 | 说明 |
|---|---|---|
| 查看当前库所有表 | show tables; | 列出当前库下的所有表 |
| 创建表 | create table 表名 (字段定义...); | 必须定义字段结构 |
| 删除表 | drop table 表名; | 危险操作,表和数据一起删除 |
2.3 常用数据类型
| 类型 | 说明 | 示例 |
|---|---|---|
int | 整数 | int,int unsigned |
varchar(n) | 变长字符串,最多 n 个字符 | varchar(40) |
decimal(m,n) | 定点小数,m 总长度,n 小数位 | decimal(10,2) |
float/double | 浮点数(不精确) | float |
2.4 字段约束
| 约束 | 说明 |
|---|---|
primary key | 主键,唯一标识一条记录 |
unsigned | 无符号(非负) |
auto_increment | 自动递增,常用于主键 |
not null | 不允许为空 |
default | 默认值 |
2.5 建表综合示例
createtabletest1(pidintunsignedprimarykeyauto_increment,pnamevarchar(40),pricedecimal(10,2),numint);字段说明:
| 字段 | 含义 | 类型与约束 |
|---|---|---|
pid | 商品主键 id | 无符号整数,自动递增 |
pname | 商品名称 | 最长 40 个字符 |
price | 商品价格 | 总长 10 位,小数保留 2 位 |
num | 商品库存数量 | 整数 |
三、数据增删改(DML)
DML(Data Manipulation Language)用于操作表中的数据:插入、更新、删除。
3.1 插入数据 insert
向表中添加新记录:
insertinto表名(字段1,字段2,...)values(值1,值2,...);示例:
insertintoproducts(name,price,stock)values('平板电脑',2999.00,50);insertintocustomers(name,phone,city)values('小红','13999999999','杭州');3.2 更新数据 update
修改表中已有的记录。一定要加 where 条件!否则会更新整张表。
update表名set字段1=新值1,字段2=新值2where条件;示例:
-- 将 id=1 的商品价格改为 5499updateproductssetprice=5499whereid=1;-- 将无线鼠标的库存增加 50updateproductssetstock=stock+50wherename='无线鼠标';危险操作提醒:如果
update不加where条件,会修改表中所有行的该字段值!
3.3 删除数据 delete
从表中删除记录。同样一定要加 where 条件!
deletefrom表名where条件;示例:
-- 删除 id=10 的商品(name 为 null 的那条)deletefromproductswhereid=10;-- 删除所有库存为 0 的商品(谨慎!)deletefromproductswherestock=0;** 危险操作提醒:**
delete from 表名不加 where 会清空整张表!delete vs drop 区别:
delete删除数据,表结构还在drop删除整张表(结构和数据都没了)
四、数据查询(DQL)
DQL(Data Query Language)用于从表中查询数据,核心是select语句。
4.1 比较运算符
| 运算符 | 含义 | 示例 |
|---|---|---|
> | 大于 | where num > 10 |
< | 小于 | where num < 10 |
>= | 大于等于 | where num >= 10 |
<= | 小于等于 | where num <= 10 |
= | 等于 | where num = 10 |
!=或<> | 不等于 | where num != 10 |
select*fromtest.test1wherenum>=10;select*fromtest.test1wherenum!=10;4.2 null 值判断
注意:null 不能使用
=或!=判断,必须用is null/is not null。
select*fromtest.test1wherepnameisnull;select*fromtest.test1wherepnameisnotnull;4.3 范围查找
| 运算符 | 含义 | 示例 |
|---|---|---|
between x and y | 在[x, y]闭区间内 | where pid between 2 and 8 |
not between x and y | 不在[x, y]区间内 | where pid not between 2 and 8 |
select*fromtest.test1wherepidbetween2and8;select*fromtest.test1wherepidnotbetween2and8;4.4 集合查询
-- 匹配集合内任意一个值select*fromtest.test1wherepidin(1,3,9);-- 不在集合内select*fromtest.test1wherepidnotin(1,3,9);4.5 模糊查询(like)
通配符
%代表任意数量的任意字符。
| 模式 | 含义 | 示例 |
|---|---|---|
'x%' | 以 x 开头 | where pname like '苹%' |
'%x' | 以 x 结尾 | where pname like '%机' |
'%x%' | 包含 x | where pname like '%手%' |
select*fromtest.test1wherepnamelike'%手%';4.6 排序
对查询结果按指定字段排序:
-- 升序(asc 可省略,默认升序)select*fromtest.test2orderbynumasc;-- 降序(desc 不可省略)select*fromtest.test2orderbynumdesc;4.7 聚合函数
对整张表的数据做统计计算,每类只返回一条统计结果。
| 函数 | 作用 | 示例 |
|---|---|---|
max(字段) | 获取最大值 | select max(num) from test.test2; |
min(字段) | 获取最小值 | select min(num) from test.test2; |
avg(字段) | 计算平均值(忽略 null) | select avg(num) from test.test2; |
sum(字段) | 计算总和 | select sum(num) from test.test2; |
count(字段) | 统计非空行数 | select count(num) from test.test2; |
count(*) | 统计总行数(含 null) | select count(*) from test.test2; |
selectmax(num)as'最大值'fromtest.test2;selectmin(num)as'最小值'fromtest.test2;selectavg(num)as'平均值'fromtest.test2;selectsum(num)as'总和'fromtest.test2;selectcount(num)as'非空数量'fromtest.test2;selectcount(*)as'总行数'fromtest.test2;
count(字段)vscount(*)区别:
count(字段)— 只统计该字段有值(非 null)的行count(*)— 统计全部行数,哪怕某字段为 null 也会计入
4.8 多表关联(join)
关联两张及以上数据表,通过匹配条件合并多表数据。
三种关联方式对比
| 关联类型 | 关键字 | 行为 |
|---|---|---|
| 内关联 | inner join | 只保留匹配成功的数据,两边不匹配的全部舍弃 |
| 左关联 | left join | 左表数据全部保留,右表无匹配补 null |
| 右关联 | right join | 右表数据全部保留,左表无匹配补 null |
-- 内关联:只展示能匹配上的数据select*fromtest.test1asainnerjointest.test2asbona.pid=b.pid;-- 左关联:左表 test1 全部保留select*fromtest.test1asaleftjointest.test2asbona.pid=b.pid;-- 右关联:右表 test2 全部保留select*fromtest.test1asarightjointest.test2asbona.pid=b.pid;小提示:
as关键字用于给表起别名,可以省略直接写test1 a。
4.9 分组与过滤(group by / having)
将查询数据按指定字段归类,相同字段值的行合并为同一组。常搭配聚合函数实现分组维度的统计。
group by— 按指定字段分组:
-- 统计每个城市的顾客数selectcity,count(*)as'人数'fromcustomersgroupbycity;having— 对分组后的结果做条件过滤。where在分组前筛选行,having在分组后筛选组,where无法替代having:
| 关键字 | 过滤时机 | 能否用聚合函数 |
|---|---|---|
where | 分组前,过滤行 | 不能 |
having | 分组后,过滤组 | 可以 |
-- 筛选顾客数大于 1 的城市(having 过滤组)selectcity,count(*)as'人数'fromcustomersgroupbycityhavingcount(*)>1;执行顺序:
where→group by→having→order by
4.10 时间函数
用于处理日期、时间类型的数据,支持时间获取、字段提取、日期运算、差值计算等。
常用时间数据类型
| 类型 | 说明 | 示例 |
|---|---|---|
date | 年月日 | '2002-12-17' |
time | 时分秒 | '12:30:45' |
datetime | 年月日时分秒 | '2002-12-17 12:30:45' |
获取当前时间
selectnow();-- 当前日期+时间:2002-12-17 12:30:45selectsysdate();-- 当前日期+时间(同 now)selectcurdate();-- 当前日期:2002-12-17selectcurrent_date;-- 同上selectcurtime();-- 当前时间:12:30:45selectcurrent_time;-- 同上时间提取函数
| 函数 | 作用 | 示例 |
|---|---|---|
year(日期) | 提取年 | year('2002-12-17')→ 2002 |
month(日期) | 提取月 | month('2002-12-17')→ 12 |
day(日期) | 提取日 | day('2002-12-17')→ 17 |
hour(时间) | 提取小时 | hour('12:30:45')→ 12 |
minute(时间) | 提取分钟 | minute('12:30:45')→ 30 |
second(时间) | 提取秒 | second('12:30:45')→ 45 |
quarter(日期) | 提取季度(1-4) | quarter('2002-12-17')→ 4 |
week(日期) | 当年第几周 | week('2002-12-17') |
dayofyear(日期) | 当年第几天 | dayofyear('2002-12-17') |
selectyear('2002-12-17'),month('2002-12-17'),day('2002-12-17');selecthour('12:30:45'),minute('12:30:45'),second('12:30:45');selectquarter('2002-12-17'),week('2002-12-17'),dayofyear('2002-12-17');-- 业务示例:查询订单的下单月份selectid,total,month(order_date)as'下单月份'fromorders;日期加减
-- 增加:date_add(基准日期, interval 数值 单位)selectdate_add('2002-12-17',interval1day);-- 2002-12-18selectdate_add('2002-12-17',interval1month);-- 2003-01-17selectdate_add('2002-12-17',interval1year);-- 2003-12-17-- 减少:date_sub(基准日期, interval 数值 单位)selectdate_sub('2002-12-17',interval1day);-- 2002-12-16selectdate_sub('2002-12-17',interval1month);-- 2002-11-17selectdate_sub('2002-12-17',interval1year);-- 2001-12-17时间差计算
-- 天数差:datediff(前日期, 后日期)selectdatediff('2006-12-17','2002-12-17');-- 1461(天)-- 单位时间差:timestampdiff(单位, 后日期, 前日期)selecttimestampdiff(year,'2002-12-17','2006-12-17');-- 4(年)selecttimestampdiff(month,'2002-12-17','2006-12-17');-- 48(月)selecttimestampdiff(day,'2002-12-17','2006-12-17');-- 1461(天)格式化日期
-- date_format(日期, '格式'),%Y四位年 %m两位月 %d两位日selectdate_format(order_date,'%Y年%m月%d日')as'下单日期'fromorders;4.11 子查询
子查询是嵌套在 SQL 语句中的查询,先执行内层,结果给外层用:
-- 标量子查询:查询价格高于平均价的商品select*fromproductswhereprice>(selectavg(price)fromproducts);-- 子查询 + in:有下过单的顾客select*fromcustomerswhereidin(selectdistinctcustomer_idfromorders);五、总结
| 分类 | 核心操作 | 关键字/语法 |
|---|---|---|
| 连接 | 登录/退出 | mysql -u root -p/exit; |
| DDL | 库操作 | create database/drop database/use/show databases |
| DDL | 表操作 | create table/drop table/show tables |
| DML | 插入 | insert into ... values ... |
| DML | 更新 | update ... set ... where ... |
| DML | 删除 | delete from ... where ... |
| DQL | 基础查询 | select ... from ... where ... |
| DQL | 条件 | =!=><>=<=is nullbetweeninlike |
| DQL | 排序 | order by ... asc/desc |
| DQL | 分组过滤 | group by ... having ... |
| DQL | 聚合 | max()min()avg()sum()count() |
| DQL | 日期时间函数 | now()year()month()date_add()datediff()等 |
| DQL | 子查询 | 嵌套select |
| DQL | 多表 | inner joinleft joinright join ... on ... |
此为MySQL 基础篇,适合零基础入门和基础复习。