MySQL基础入门
2026/7/19 3:55:07 网站建设 项目流程

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%'包含 xwhere 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;

执行顺序wheregroup byhavingorder 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 基础篇,适合零基础入门和基础复习。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询