☰
数据库常用语句自查
2026/10/8 13:11:42 网站建设 项目流程

数据库常用语句自查文档(MySQL)

自查口诀:写前想条件、写后看行数、删改必带 where、事务必须 commit/rollback。


一、DDL 数据定义

创建数据库

createdatabase[ifnotexists]<库名>defaultcharset<字符集>;
createdatabaseifnotexistsshopdefaultcharsetutf8mb4;

删除数据库

dropdatabase[ifexists]<库名>;
dropdatabaseifexistsshop;

创建表

createtable<表名>(<字段><类型>[约束],...);
createtableuser(idintprimarykeyauto_increment,namevarchar(50)notnull,ageintdefault18,created_atdatetimedefaultcurrent_timestamp);

删除表

droptable[ifexists]<表名>;
droptableifexistsuser;

清空表

truncatetable<表名>;
truncatetableuser;

加列

altertable<表名>addcolumn<字段><类型>[约束];
altertableuseraddcolumnemailvarchar(100);

改列类型

altertable<表名>modifycolumn<字段><新类型>;
altertableusermodifycolumnageintdefault0;

改列名

altertable<表名>changecolumn<旧名><新名><类型>;
altertableuserchangecolumnname usernamevarchar(50);

删列

altertable<表名>dropcolumn<字段>;
altertableuserdropcolumnemail;

改表名

renametable<旧表名>to<新表名>;
renametableusertousers;

创建索引

create[unique]index<索引名>on<表名>(<字段>);
createindexidx_nameonuser(username);

删除索引

dropindex<索引名>on<表名>;
dropindexidx_nameonuser;

创建视图

create[orreplace]view<视图名>as<select...>;
createviewv_adultasselect*fromuserwhereage>=18;

删除视图

dropview[ifexists]<视图名>;
dropviewifexistsv_adult;

约束速查

建表时内联使用:

primary key 主键 not null 非空 unique 唯一 default <值> 默认值 auto_increment 自增 check (<条件>) 检查约束 foreign key (<字段>) references <主表>(<字段>) 外键

二、DML 数据操作

插入单条

insertinto<表名>(<字段1>,<字段2>)values(<值1>,<值2>);
insertintouser(name,age)values('张三',25);

插入多条

insertinto<表名>(<字段1>)values(<v1>),(<v2>),(<v3>);
insertintouser(name)values('a'),('b'),('c');

查询结果插入

insertinto<目标表>select<字段>from<源表>;
insertintouser_backupselect*fromuser;

更新

update<表名>set<字段>=<值>where<条件>;
updateusersetage=26wherename='张三';

多表更新

update<表a>join<表b>on<关联条件>set<a.字段>=<值>where<条件>;
updateorderojoinuseruono.uid=u.idseto.name=u.namewhereu.age>18;

删除

deletefrom<表名>where<条件>;
deletefromuserwhereageisnull;

⚠️ update / delete 不写 where = 全表操作!
先写select count(*) ... where 同条件确认行数再动手。


三、DQL 数据查询

查全部

select*from<表名>;
select*fromuser;

查指定列

select<字段1>,<字段2>from<表名>;
selectid,namefromuser;

别名

select<字段>as<别名>from<表名>;
selectnameas用户名fromuser;

去重

selectdistinct<字段>from<表名>;
selectdistinctagefromuser;

条件查询

select*from<表名>where<条件>;
select*fromuserwhereage>=18andstatus=1;

区间 between

<字段>between<最小值>and<最大值>
whereagebetween18and60

集合 in / not in

<字段>in(<值1>,<值2>)
whereidin(1,2,3)

模糊 like

<字段>like'<模式>'
  • %匹配任意多个字符
  • _匹配单个字符
wherenamelike'张%'-- 张开头wherenamelike'张_'-- 张三、张四(两个字)wherenamelike'%小明%'-- 只要包含"小明"

正则 regexp

<字段>regexp'<表达式>'
wherenameregexp'^张[三四]$'

空值判断

<字段>isnull<字段>isnotnull
whereageisnotnull

取反

not<条件>
wherenot(agebetween18and60)

排序

orderby<字段>asc|desc

多列:

orderbyagedesc,idasc

分页

limit<偏移量>,<条数>
limit10,20-- 第 11~30 条

偏移量 = (页码 - 1) × 每页条数

聚合函数

selectcount(*)fromuserwhereage>18;selectsum(price)fromorder;selectavg(price)fromorder;selectmax(price)fromorder;selectmin(price)fromorder;selectcount(distinctage)fromuser;

分组 group by

select<分组字段>,<聚合函数>from<表名>groupby<分组字段>;
selectdept_id,count(*)fromempgroupbydept_id;

分组后过滤 having

select<分组字段>,<聚合函数>from<表名>groupby<分组字段>having<聚合条件>;
selectdept_id,count(*)ascfromempgroupbydept_idhavingc>5;

where 在 group by 之前执行,having 在 group by 之后执行。

连表 join

select...from<表a>[inner|left|right]join<表b>on<关联条件>;
selectu.name,o.totalfromuseruleftjoinorderoonu.id=o.uid;

合并结果 union

select<字段>from<表a>union[all]select<字段>from<表b>;
selectnamefromstuunionallselectnamefromteacher;

标量子查询

where<字段>=(select...);
wheresalary=(selectmax(salary)fromemp);

in 子查询

where<字段>in(select...);
wheredept_idin(selectidfromdeptwherecity='北京');

exists 子查询

whereexists(select1from<表b>where<关联条件>);
whereexists(select1fromorderowhereo.uid=user.id);

条件分支 case when

casewhen<条件>then<结果>else<默认>end
selectname,casewhenage>=18then'成年'else'未成年'endas类型fromuser;

窗口函数:行号

row_number()over(partitionby<分组字段>orderby<排序字段>desc)asrn
select*,row_number()over(partitionbydept_idorderbysalarydesc)asrnfromemp;

窗口函数:累计

sum(<字段>)over(partitionby<分组字段>orderby<排序字段>)as<别名>
selectuid,amount,sum(amount)over(partitionbyuidorderbycreated_at)as累计fromorder;

四、TCL 事务

starttransaction;updateaccountsetbalance=balance-100whereid=1;savepointsp1;-- 可选:设置保存点updateaccountsetbalance=balance+100whereid=2;commit;-- 提交,或 rollback to sp1 回滚到保存点,或 rollback 全部回滚

忘记 commit 会锁行 → 查show processlist看Waiting for commit。


五、DCL 权限

创建用户

createuser'<用户名>'@'<主机>'identifiedby'<密码>';
createuser'app'@'localhost'identifiedby'pass123';

授权

grant<权限>on<库>.<表>to'<用户>'@'<主机>';
grantselect,insert,updateonshop.*to'app'@'localhost';

全部权限

grantallprivilegeson<库>.<表>to'<用户>'@'<主机>';
grantallprivilegesonshop.*to'app'@'localhost';

生效

flushprivileges;
flushprivileges;

回收权限

revoke<权限>on<库>.<表>from'<用户>'@'<主机>';
revokedeleteonshop.*from'app'@'localhost';

删除用户

dropuser'<用户名>'@'<主机>';
dropuser'app'@'localhost';

六、常用函数

字符串函数

concat('a','b')-- 拼接substring('hello',2,3)-- 截取:elllength('你好')-- 长度(utf8 下 6)char_length('你好')-- 字符数:2upper('abc')-- 大写:ABClower('ABC')-- 小写:abctrim(' abc ')-- 去空格:abcreplace('abc','b','x')-- 替换:axcleft('abcde',2)-- 左取:abright('abcde',2)-- 右取:delocate('bc','abcde')-- 查找位置:2

数值函数

round(3.1415,2)-- 四舍五入:3.14ceil(3.14)-- 向上取整:4floor(3.14)-- 向下取整:3abs(-5)-- 绝对值:5mod(10,3)-- 取余:1rand()-- 随机数 0~1

日期函数

now()-- 当前日期时间curdate()-- 当前日期curtime()-- 当前时间date_format(now(),'%Y-%m-%d')-- 格式化date_add(now(),interval30day)-- 加 30 天datediff('2025-01-10','2025-01-01')-- 相差天数:9year(now())-- 提取年份month(now())-- 提取月份day(now())-- 提取日

常用示例:

-- 近 30 天数据select*fromorderwherecreated_at>=date_add(curdate(),interval-30day);-- 本月第一天select*fromorderwherecreated_at>=date_format(curdate(),'%Y-%m-01');

条件函数

if(条件,真值,假值)-- 三目运算ifnull(x,默认值)-- null 兜底coalesce(a,b,c)-- 返回首个非 null
selectif(age>=18,'成年','未成年')fromuser;selectifnull(phone,'无电话')fromuser;selectcoalesce(a.phone,b.phone,'无电话')fromuser;

七、排查与元数据

查看库表

showdatabases;showtables;

查看表结构

desc<表名>;
descuser;

查看建表语句

showcreatetable<表名>;
showcreatetableuser;

查看索引

showindexfrom<表名>;
showindexfromuser;

执行计划

explain<select...>;
explainselect*fromuserwhereage>18;

重点看type、key、rows是否走索引。

查看运行进程

showprocesslist;

查慢 sql / 锁。

查看字符集

showvariableslike'character_set%';

查看变量

showvariableslike'<模式>';
showvariableslike'slow_query%';

慢查询自查

showglobalstatuslike'Slow_queries';
-- 发现慢查询数高 → 用 explain 分析explainselect*fromorderwherestatus=0;-- 如果看到 type = all 且没走索引 → 补索引

附:10 条金句

  1. 删改必带 where,先select count(*) where 同条件确认行数后执行。

  2. 分页偏移量 = (页码 - 1) × 每页条数。

  3. where 在 group by 之前执行,having 在 group by 之后执行。

  4. join 一定写 on,left join 的副表条件放 on 里(放 where 里会变 inner join)。

  5. 字符串用单引号'',null 判断用is null不用=。

  6. like 以%开头索引失效,前缀匹配才能走索引。

  7. 多行插入、批量 update 记得包事务。

  8. explain 看 type:const > eq_ref > ref > range > index > all,all 要警惕。

  9. 日期字段比较用日期函数格式化,别对列做函数(如date_format(列, ...))否则索引失效。

  10. 备份先select ...验证,dml 前检查autocommit。

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

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

立即咨询