数据库与 SQL · 第 3 / 11 章 · 本章 4 小节
3查询基础
上一章把表结构、主键、唯一键和索引摆清楚了,也定下一个前提:数据库里的每一行,都应该对得上某一次业务动作。 这一章开始动手查。查询对测试来说不是「顺便看看数据」,而是取证:接口返回和预期不一致时,先看库里究竟写了什么, 才能把责任划到服务端逻辑、异步任务,还是自己的造数脚本上。
先钉死数据。本模块统一用一套订单域表:订单主表 t_order、订单明细 t_order_item、支付流水 t_pay_flow、优惠券 t_coupon,后面每一章都用这一套,完整 DDL 在第 9 章给出;下面是我用 show create table 抄回来的、本章会用到的列,字段名和状态取值都与第 9 章一致。另外两张 t_stock(库存)和 api_log(接口日志)只是本章为了演示查询才用到的辅助示例表,不属于订单域:
-- 订单域统一用这一套表,这里只列本章会用到的列,完整 DDL 见第 9 章 create table t_order ( order_id bigint primary key, user_id bigint not null, total_amount decimal(10,2) not null, discount_amount decimal(10,2) not null default 0.00, pay_amount decimal(10,2) not null, status tinyint default null, -- 10待支付 20已支付 30已发货 40已完成 50已取消 60已退款,历史数据为 null create_time datetime not null, pay_time datetime default null ); create table t_pay_flow ( flow_id bigint primary key, order_id bigint not null, channel tinyint not null, -- 1微信 2支付宝 3余额 pay_amount decimal(10,2) not null, pay_status tinyint not null, -- 10处理中 20成功 30失败 create_time datetime not null ); create table t_coupon ( coupon_id bigint primary key, coupon_code varchar(32) not null, user_id bigint not null, order_id bigint default null, -- 未使用时为 null status tinyint not null, -- 10未使用 20已使用 30已过期 use_time datetime default null ); create table t_stock ( sku_id bigint primary key, sku_code varchar(32) not null, total_qty int not null, locked_qty int not null default 0, sold_qty int not null default 0 ); create table api_log ( log_id bigint primary key, api_name varchar(64) not null, order_id bigint default null, http_code int not null, error_code varchar(32) default null, cost_ms int default null, create_time datetime not null );
注意 t_order.status、t_order.pay_time、t_coupon.order_id 都允许为 null:
历史数据只回填了一半、未支付订单没有支付时间、优惠券发了还没用。这三处 null 就是本节一半陷阱的来源。
顺带说明:t_stock 是库存侧的辅助示例表,api_log 是另一张与订单域无关的接口日志示例表,两者都只在本章用来演示查询。
3.1 select / where / order by / limit
先写最小可用的查询。我要查用户 10086 最近的订单,只看校验会用到的列:
select order_id, status, pay_amount, create_time, pay_time from t_order where user_id = 10086 and create_time >= '2025-03-01 00:00:00' order by create_time desc, order_id desc limit 20;
书写顺序是 select → from → where → order by → limit,执行顺序却是 from → where → select → order by → limit。 所以 where 里不能引用 select 起的别名,别名在过滤之后才算出来。
order by 为什么写两列?同一秒创建的订单很多,只按 create_time 排序时,
这些行的相对顺序由存储引擎决定,每次执行都可能不同。验证分页时,这会让你看到「第二页出现了第一页的订单」,
于是怀疑代码——其实是 SQL 没定序。把主键追加为最后一个排序字段,结果就稳定了;
我通常直接写 order by order_id desc,自增主键和时间同向,而且绝对唯一。
where 的运算符没有语法难点,难点是它们遇到 null 时的行为完全不符合直觉:
比较用 =、<>(或 !=,两者等价)、<、<=、>、>=;
集合用 in、not in;区间用 between ... and ...;模糊用 like;
判空用 is null、is not null。
SQL 用的是三值逻辑:表达式的结果可以是 true、false、unknown。null 表示「不知道」,
所以「不知道的值 = 20」的结果不是 false 而是 unknown,而 where 只保留 true 的行。
下表假设 t_order 共 1000 行,status 有 812 行不是 null、188 行是 null:
| 条件写法 | 对 status 为 null 的 188 行 | 命中行数 | 怎么理解 |
|---|---|---|---|
status = 20 | 不命中 | 437 | unknown 被当假处理,符合直觉 |
status <> 20 | 不命中 | 375 | 最坑的一条:812-437=375,null 行既不算等于也不算不等于 |
status is null | 命中 | 188 | 唯一正确的判空写法 |
status = null | 不命中 | 0 | 永远返回空集,而且不报错,所以很难发现 |
status in (20,30) | 不命中 | 793 | in 等价于一串 = 用 or 连起来 |
status not in (20) | 不命中 | 375 | 不要以为它等于「非 20 的全部」 |
status not in (20, null) | 不命中 | 0 | 列表里带 null,整个 not in 恒为 unknown |
ifnull(status,0) <> 20 | 命中 | 563 | 先兜底再比较,结果才符合人的预期 |
coalesce(status,0) = 0 | 命中 | 188 | coalesce 取第一个非 null 值,可以给多个候选 |
这张表怎么用?写下任何比较运算符之前,先问一句「这一列允许 null 吗」。
我验证「状态不是 20 的订单数」时踩过一次:接口返回 375,我按直觉预期 563,差的 188 就是没回填 status 的历史订单。
定责第一步不是改代码,而是跑 select count(*) from t_order where status is null; 确认数据本身缺失。
「查一下哪些订单没有支付成功记录」是很自然的测试需求,新手会写
select * from t_order where order_id not in (select order_id from t_pay_flow);。
只要 t_pay_flow.order_id 里有一行是 null(渠道回调没带订单号写进来的脏数据),
这条语句返回的就是空集,而不是「没支付的订单」。它不报错、不警告,你只会以为全都支付过了。
要么补上 where order_id is not null,要么直接换成 exists——我推荐后者,语义上就没有这个坑。
like 里 % 匹配任意长度,_ 匹配恰好一个字符;以 % 开头的模式无法使用索引,
在千万行的日志表上会扫全表。另外 order_id 是 bigint,写 where order_id like '100%' 时
MySQL 会把整列转成字符串再比,索引直接失效——这类隐式类型转换的特征是结果对但特别慢,
用 explain 看 type 列会从 ref 变成 ALL。
between a and b 是闭区间,两端都包含,用在日期上最容易出事:
between '2025-03-01' and '2025-03-31' 的第二个值会被当成 '2025-03-31 00:00:00',
3 月 31 日白天的订单全部漏掉。我固定用左闭右开:
-- 错误:3 月 31 日白天的订单全漏,只少不多,不报错 select count(*) from t_order where create_time between '2025-03-01' and '2025-03-31'; -- 正确:左闭右开,右边界指向下个月 1 号 select count(*) from t_order where create_time >= '2025-03-01' and create_time < '2025-04-01'; -- 验证有没有漏:最大时间应落在 3 月 31 日 select min(create_time) as first_at, max(create_time) as last_at, count(*) as cnt from t_order where create_time >= '2025-03-01' and create_time < '2025-04-01';
分页是 limit 20 取前 20 行,limit 20 offset 40(也可写 limit 40, 20)跳过 40 行再取 20 行。
两件事必须记住:没有 order by 的 limit 结果是不确定的,同一句 SQL 连跑两次可能给你不同的行;
offset 很大时性能会崩,数据库要先取出前 20 万行再丢掉,翻到第 10000 页的接口慢,未必是业务逻辑的问题。
顺带说 null 对输出的影响,这一条直接决定接口返回 200 还是 500。用 Go 读这张表时,
最容易犯的错是把可能为 null 的列直接 Scan 进 string:
rows, err := db.Query("select order_id, status, pay_time from t_order where order_id = ?", 20250331001)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var (
orderID int64
status sql.NullString // 不能用 string:status 允许为 null
payTime sql.NullTime
)
if err := rows.Scan(&orderID, &status, &payTime); err != nil {
return err
}
if status.Valid {
fmt.Printf("order=%d status=%s\n", orderID, status.String)
} else {
fmt.Printf("order=%d status=<null>\n", orderID) // 区分「没值」和「空字符串」
}
}
如果这里用了 var status string,运行时就会拿到
sql: Scan error on column index 1, name "status": converting NULL to string is unsupported。
这条报错的诊断价值在于:它证明了「库里有 null」和「接口返回 500」的因果关系,
提 bug 时把它和上面那句判空 count 的结果一起贴上,开发就不用再来回猜。
3.2 聚合与 group by / having
统计类校验全靠聚合函数:count 数行数、sum 求和、avg 求平均、
max / min 取极值、group_concat 拼字符串。
它们的输出对不对,取决于你清楚数据库在哪一步算了它们。执行顺序是:
- from / join:取出参与查询的行集,此时还没有任何过滤。
- where:逐行过滤。这一步还没有分组,所以 where 里不能写
count(*)、sum()。 - group by:把剩下的行按指定列切成组。
- 聚合函数:对每一组算出 count / sum / avg,得到「一行代表一组」。
- having:按聚合结果过滤组,这里才能写
count(*) > 100。 - select:挑出最终列,算别名。
- order by / limit:排序、截断。
记住这条链路,两个常见问题就自解了:where count(*) > 100 报错,是因为 where 执行时分组还没发生;
having 里能引用 select 的别名,是因为 having 在 select 之后求值。别名引用是 MySQL 方言,我写脚本时宁可重复写表达式。
下面这条 SQL 我故意写错了一处,希望你记住报错原文:select 列表里的 channel 没有出现在
group by 里,MySQL 5.7 之后的严格模式会直接拒绝。
mysql> select channel, pay_status, count(*) from t_pay_flow group by pay_status; ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'order_db.t_pay_flow.channel' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by -- 先确认模式是否开着 mysql> select @@sql_mode; +-------------------------------------------------------------+ | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,... | +-------------------------------------------------------------+ -- 写法一:channel 也进 group by select channel, pay_status, count(*) as cnt from t_pay_flow where create_time >= '2025-03-01' and create_time < '2025-04-01' group by channel, pay_status order by cnt desc; -- 写法二:只按 pay_status 分组 select pay_status, count(*) as cnt, sum(pay_amount) as amt from t_pay_flow where create_time >= '2025-03-01' and create_time < '2025-04-01' group by pay_status having cnt > 0 order by cnt desc;
报错里那句 ONLY_FULL_GROUP_BY 值得多看一眼。它开着时,
「group by 之外且不在聚合函数里」的列一律拒绝;关掉之后 MySQL 会随便从组里挑一行的值返回,
同一个查询每次可能给出不同的 channel。所以这条错误其实在保护你:
某个列你不确定它在一组里是否唯一,就说明这个查询的输出本身就不确定,拿它当断言依据会得到随机失败的用例。
接下来是这一节最要紧的差异:count(*) 数行数,count(字段) 数这个字段非 null 的行数。
我在 t_order 上实测了一遍:
mysql> select count(*) as rows_all, count(status) as rows_status,
-> count(distinct order_id) as rows_order
-> from t_order;
+----------+-------------+------------+
| rows_all | rows_status | rows_order |
+----------+-------------+------------+
| 1000 | 812 | 1000 |
+----------+-------------+------------+
-- avg 的分母受影响:63 行 cost_ms 为 null
mysql> select avg(cost_ms) as avg_only_notnull,
-> sum(cost_ms) / count(*) as avg_all_rows,
-> count(cost_ms) as notnull_rows, count(*) as all_rows
-> from api_log;
+------------------+--------------+--------------+----------+
| avg_only_notnull | avg_all_rows | notnull_rows | all_rows |
+------------------+--------------+--------------+----------+
| 186.42 | 174.68 | 937 | 1000 |
+------------------+--------------+--------------+----------+
两个数差 11.74 毫秒(186.42 - 174.68),都叫「平均耗时」,谁对?取决于你要回答什么:
问「成功的请求平均多慢」用 avg(cost_ms),问「这个接口整体摊下来的成本」用 sum(cost_ms)/count(*)。
真正让测试翻车的是拿 avg 算的基线去和监控大盘比,对不上就以为数据有问题——
先把 count(cost_ms) 和 count(*) 都打出来,看有没有 null 作祟,再谈谁对谁错。下表把每个函数对 null 的态度列清楚:
| 写法 | 数的是什么 | 遇到 null | 测试里用它做什么 |
|---|---|---|---|
count(*) | 行数,与列无关 | 整行全 null 也算一行 | 对账总数、分页接口的 total |
count(1) | 同 count(*) | 同上 | 等价写法,性能没差别,写哪个都行 |
count(status) | status 非 null 的行数 | 跳过 null 行 | 查字段未回填:count(*) - count(status) = 188 |
count(distinct order_id) | 去重后的取值个数 | null 不计入 | 判断一对多是否重复写入 |
sum(x) | 非 null 值之和 | 跳过 null;全为 null 时返回 null | 金额对账,先确认被跳过的行该不该是 null |
avg(x) | sum / 非 null 行数 | 分母变小,结果偏移 | 耗时基线,用之前先看 count(x) |
max(x) / min(x) | 极值 | 跳过 null;全为 null 返回 null | 取最近一次支付时间、最大耗时 |
group_concat(x) | 把多行拼成一个字符串 | 跳过 null | 排错时把同一订单的所有状态一次看全 |
我现在写数据校验脚本,会把「总数」和「有效数」一起断言,而不是只断言一个:
select count(*) as total, count(status) as valid from t_order;。
只要 total - valid 不为 0,脚本就打印一行提示,说明有多少行因为字段为 null 无法参与分类统计。
指标对不上时,你能立刻分清是「数据缺失」还是「统计口径错了」。
还有一处 null 与分组的交互:group by status 时,status 为 null 的行会
聚成单独一组,结果显示为一行 NULL,所以 select status, count(*) from t_order group by status;
会给你 7 行而不是 6 行。按「状态只有 6 种」写断言会被这第 7 行绊住——它通常是有意义的信号:
有一批订单从没被任何流程改过状态。
3.3 子查询的三种写法
真实校验几乎都要「用一张表的条件去筛另一张表」。子查询可以出现在三个位置,混用会得到静默错误的结论。
第一种:标量子查询,放在 select 或 where 里,期望返回一行一列。 我拿它给订单补一个「实际支付金额」:
-- 补一列支付金额
select o.order_id, o.pay_amount,
(select p.pay_amount from t_pay_flow p
where p.order_id = o.order_id and p.pay_status = 20) as paid_amount
from t_order o
where o.user_id = 10086
order by o.order_id desc
limit 10;
-- 有两条 pay_status = 20 的支付记录时立刻失败:
ERROR 1242 (21000): Subquery returns more than 1 row
-- 先探雷:查出非空说明存在重复支付
select order_id, count(*) as cnt
from t_pay_flow
where pay_status = 20
group by order_id
having cnt > 1
order by cnt desc
limit 10;
标量子查询有两个必须知道的行为。返回多行会报 ERROR 1242,这还算好,因为它是硬失败;
更麻烦的是返回零行时结果不是 0 而是 null,而 null 参与比较是 unknown,
条件不成立、行被静默丢弃。所以 where (select ...) = 100 会连「查不到」的订单一起过滤掉,行数变少却没有提示。
我用它只有两个前提:能证明子查询唯一(比如按主键查),且字段缺失时返回 null 是可接受的。
第二种:in 子查询,用来做「存在」判断。
这是我最常用的一种,因为它天然不会重复放大行数:
-- 3 月份支付成功的订单 select order_id, user_id, pay_amount, status from t_order where create_time >= '2025-03-01' and create_time < '2025-04-01' and order_id in (select order_id from t_pay_flow where pay_status = 20) order by order_id desc limit 20; -- 危险:子查询里有 null 就成了空集 select order_id from t_order where order_id not in (select order_id from t_pay_flow); -- 安全写法一:先排掉 null select order_id from t_order where order_id not in (select order_id from t_pay_flow where order_id is not null); -- 安全写法二(推荐):换成 exists select o.order_id from t_order o where not exists (select 1 from t_pay_flow p where p.order_id = o.order_id);
in 子查询的语义是半连接:左表某行只要在子查询结果里出现过一次就输出一次,
绝不因为右表有多行而输出多次。这在统计时价值极大——一个订单有 2 条支付记录时,
用 in 统计还是 1 个订单,用 join 就变成 2 个。
MySQL 8.0 会把非相关 in 子查询改写成 semi-join;而 not in 因为要处理 null 语义往往改写不成,
慢且容易出错,这就是我推荐一律换成 not exists 的原因。
第三种:from 子查询,也叫派生表,把子查询的结果当成一张临时表再用。 典型场景是先把明细聚合成中间结果,再对它做二次计算:
-- 各渠道成功率:先算分子分母,再算比率
select t.channel,
t.total_cnt,
t.success_cnt,
round(t.success_cnt / t.total_cnt * 100, 2) as success_rate
from (
select channel,
count(*) as total_cnt,
sum(case when pay_status = 20 then 1 else 0 end) as success_cnt
from t_pay_flow
where create_time >= '2025-03-01' and create_time < '2025-04-01'
group by channel
) t
where t.total_cnt >= 100
order by success_rate asc;
-- 漏写别名:
ERROR 1248 (42000): Every derived table must have its own alias
派生表有两个细节:必须给别名(上面那个 t),否则报 ERROR 1248;
5.7 之前 MySQL 会把它物化成临时表,数据量大时很慢,8.0 能合并的会被合并。
不过这里 where t.total_cnt >= 100 完全可以用 having 写进子查询,结果一样;
所以 from 子查询在测试里更多是用来拼对账中间结果,比如先算订单侧的应付金额,再和支付侧的实付金额做差。
三种写法加上 exists 和 join,怎么选?我把标准压成一张表。
最关键的一列是「返回行数」,因为行数一变,后面所有的 count 和 sum 都会跟着变:
| 写法 | 返回行数 | 能带出另一张表的列吗 | 遇到 null | 我用它做什么 |
|---|---|---|---|---|
| 标量子查询 | 与主表一致 | 只能带一列 | 查不到时返回 null,比较条件静默失效 | 按主键补一个唯一值,如一单一次支付 |
in 子查询 | 与主表一致(去重语义) | 不能 | 子查询结果含 null 会影响 not in | 只要判断「存在」,如哪些订单支付过 |
exists | 与主表一致,命中即停 | 不能 | 不受 null 影响 | 存在判断的默认写法,右表很大时尤其合适 |
from 子查询 | 由子查询决定 | 全部列都可以 | 跟随子查询结果 | 先聚合再算比率,或拼对账中间结果 |
join | 可能放大(一对多时按多行输出) | 全部列都可以 | null 匹配不上,left join 会补 null 行 | 需要两端字段同屏、或故意要看重复数据 |
我做过支付渠道的日报校验:三月份 t_pay_flow 有 12,000 行,pay_status = 20 的有 10,200 行,成功率 85%。
为了「顺便看看订单信息」,我写成
select count(*) from t_pay_flow p join t_order o on o.order_id = p.order_id where p.pay_status = 20;,
结果得到 11,730 行——t_order 里有 1,530 个订单在灰度期间被双写留下了重复行。
我拿这个数去提 bug,开发查了两小时才发现是我的 SQL 放大。
教训:join 之后统计任何东西,分子分母都要重新想一遍,必要时用 count(distinct p.flow_id)。
所以「为什么有时 join 更好」的答案是:当你要的就是另一张表的列,或者你要看的就是重复行本身 (比如确认一个订单一共有几条支付记录),join 不可替代;而当你要的只是「另一张表里有没有」, join 不但多余,还会因为放大行数给出错误的统计量。这两种需求读 SQL 时一眼可辨:select 列表里有没有对方的列。
3.4 测试最常用的 10 条查询
下面十条是我重复写得最多的。它们都能单独执行、不依赖任何工具、都能直接贴进 bug 单当证据,字段名对齐上面的表结构(与第 9 章的 DDL 一致)。每条我都补了两件事:它回答什么问题,以及结果该有几行——行数本身就是判据,出现不该出现的行就是缺陷信号。
| # | 场景 | 它回答什么问题 | 结果该有几行、出现几行说明什么 |
|---|---|---|---|
| 1 | 查某用户全部订单 | 复现用户投诉:这个用户有多少单、状态分别是什么 | 期望与该用户真实单数一致(通常几行到几十行);比页面说的少,先查是不是 status 为 null 的行被条件排掉了 |
| 2 | 查某订单的完整链路 | 一个订单的支付、优惠券、库存三侧记录是否齐全 | 成功支付的单:支付侧只有 1 行成功流水、券 1 行且 order_id 指回本单、库存 1 行;支付侧 0 行是回调没落库,成功流水 2 行以上就是重复支付 |
| 3 | 查某接口最近失败记录 | 最近的失败原文、错误码、耗时 | 期望 0 行(或只剩已知的历史失败);同一个 error_code 成批出现,说明是系统性缺陷而不是偶发 |
| 4 | 查某订单的接口调用轨迹 | 定责:请求有没有到、到过几次、每次什么结果 | 期望与页面上的操作次数一致;同一个下单/支付接口出现两次成功记录,就是重复提交没做幂等 |
| 5 | 统计状态分布 | 状态比例是否符合预期,有没有异常状态 | 有 null 时是 7 行(status_name = 0 那一行就是 null 组,见 3.1);出现 0 以外的表外取值才是异常,0 那一行的占比要单独看 |
| 6 | 查重复数据 | 一单多笔成功支付、一条记录被写两次 | 期望 0 行;出现 1 行就是缺陷,把 flow_id 和金额一起贴进 bug 单 |
| 7 | 查悬空数据 | 有订单没支付、有优惠券没绑订单 | 期望只剩 10(待支付)这类还没付款的单;20/30/40/60 出现在结果里,就是回调没落库或状态机漏了(50 已取消已被条件排除,本就不该出现) |
| 8 | 金额对账 | 应付 - 优惠 = 实付,支付侧金额是否与订单侧一致 | 期望 0 行;出现任何一行都是账不平,先看 paid_sum 是不是被 null 顶成了 0 造成的假差额 |
| 9 | 查优惠券超发与重复使用 | 券被多次核销,或用在不适用的订单上 | 期望 0 行;出现说明同一张券被核销了多次,或标记已使用却没回写 order_id |
| 10 | 查库存异常 | 可售为负、锁定未释放、超卖 | 期望 0 行;可售量为负就是超卖;locked_qty 长期不降、且对应订单已完成,就是锁定没释放 |
第一组是定位类,特点是把范围收得尽量小(一个用户、一个订单、一个接口),保证几秒内出结果:
-- 1. 查某用户全部订单 select order_id, status, total_amount, discount_amount, pay_amount, create_time, pay_time from t_order where user_id = 10086 order by create_time desc, order_id desc; -- 2. 查某订单的完整链路 -- 2.1 支付侧(可能多条) select flow_id, channel, pay_amount, pay_status, create_time from t_pay_flow where order_id = 20250331001 order by create_time; -- 2.2 优惠券侧:order_id 可能为 null select coupon_id, coupon_code, user_id, status, order_id, use_time from t_coupon where order_id = 20250331001 or (user_id = 10086 and status = 10); -- 2.3 库存侧:看 locked_qty 是否残留 select sku_id, sku_code, total_qty, locked_qty, sold_qty from t_stock where sku_code = 'SKU-2025-0317'; -- 3. 查某接口最近失败记录 select log_id, api_name, order_id, http_code, error_code, cost_ms, create_time from api_log where api_name = '/api/v1/order/pay' and (http_code >= 400 or error_code is not null) order by create_time desc limit 50; -- 4. 查某订单的接口调用轨迹 select log_id, api_name, http_code, error_code, cost_ms, create_time from api_log where order_id = 20250331001 order by create_time;
第二组是统计类,几乎都会出现在同一个数据一致性校验脚本里。执行前先想清楚每条的分子分母,
别让 count 的语义差异和 join 的行数放大混进来:
-- 5. 统计状态分布(null 单独成组)
select ifnull(status, 0) as status_name, count(*) as cnt
from t_order
where create_time >= '2025-03-01' and create_time < '2025-04-01'
group by ifnull(status, 0)
order by cnt desc;
-- 6. 查重复数据:同一订单多笔成功支付
-- 必须带上 pay_status = 20:失败后重试成功本来就有两行(30 失败 + 20 成功),那不是缺陷
select order_id,
count(*) as pay_cnt,
count(distinct pay_status) as status_kinds,
group_concat(concat(flow_id, ':', pay_status, ':', pay_amount) order by flow_id) as detail
from t_pay_flow
where create_time >= '2025-03-01' and create_time < '2025-04-01'
and pay_status = 20
group by order_id
having pay_cnt > 1
order by pay_cnt desc
limit 50;
-- 7. 查悬空数据:有订单无支付(用 exists)
select o.order_id, o.user_id, o.status, o.pay_amount, o.create_time
from t_order o
where o.create_time >= '2025-03-01' and o.create_time < '2025-04-01'
and (o.status is null or o.status <> 50) -- status 可为 null,直接写 status <> 50 会把这批历史数据静默排除
and not exists (select 1 from t_pay_flow p where p.order_id = o.order_id)
order by o.create_time desc
limit 50;
-- 8. 金额对账:应付 - 优惠 = 实付
select o.order_id,
o.total_amount,
o.discount_amount,
o.pay_amount,
o.total_amount - o.discount_amount as expect_pay,
ifnull(sum(case when p.pay_status = 20 then p.pay_amount end), 0) as paid_sum
from t_order o
left join t_pay_flow p on p.order_id = o.order_id
where o.create_time >= '2025-03-01' and o.create_time < '2025-04-01'
group by o.order_id, o.total_amount, o.discount_amount, o.pay_amount
having paid_sum <> o.pay_amount
or o.pay_amount <> o.total_amount - o.discount_amount
order by o.order_id desc
limit 50;
-- 9. 优惠券异常:多次核销或没关联订单
select c.coupon_id, c.user_id,
count(*) as used_cnt,
group_concat(c.order_id order by c.use_time) as order_ids
from t_coupon c
where c.status = 20
group by c.coupon_id, c.user_id
having used_cnt > 1 or order_ids is null
order by used_cnt desc
limit 50;
-- 10. 库存异常:可售为负或锁定超总量
select sku_id, sku_code, total_qty, locked_qty, sold_qty,
total_qty - locked_qty - sold_qty as available_qty
from t_stock
where total_qty - locked_qty - sold_qty < 0
or locked_qty > total_qty
order by available_qty asc;
第三组是造数与清理。造数的原则是让脚本可重复地生成同一批数据; 清理的原则是先 select 数清楚要删多少行,再删:
-- 造数:固定 ID 段,重复执行不冲突 insert into t_order (order_id, user_id, total_amount, discount_amount, pay_amount, status, create_time, pay_time) values (99000001, 99001, 199.00, 0.00, 199.00, 10, date_sub(now(), interval 2 day), null), (99000002, 99001, 299.00, 30.00, 269.00, 20, date_sub(now(), interval 1 day), date_sub(now(), interval 1 day)), (99000003, 99002, 399.00, 50.00, 349.00, null, now(), null); -- 造支付记录:pay_status = 20 与 30 各一条 insert into t_pay_flow (flow_id, order_id, channel, pay_amount, pay_status, create_time) values (99000101, 99000002, 1, 269.00, 20, date_sub(now(), interval 1 day)), (99000102, 99000003, 2, 349.00, 30, now()); -- 验证造数结果:必须正好 3 行、2 行 select count(*) as orders_cnt from t_order where order_id between 99000001 and 99000003; select count(*) as pay_cnt from t_pay_flow where order_id between 99000001 and 99000003; -- 清理:先看要删多少再删;绝不写无 where 的 delete select count(*) as will_delete from api_log where api_name = '/api/v1/order/pay' and create_time < date_sub(now(), interval 7 day); delete from api_log where api_name = '/api/v1/order/pay' and create_time < date_sub(now(), interval 7 day) limit 5000; delete from t_order where order_id between 99000001 and 99000003; delete from t_pay_flow where order_id between 99000001 and 99000003;
一、先 select 同条件确认行数再删。把 delete 换成 select count(*) 就能得到待删行数,
这一步花两秒,能避免一次事故。
二、绝不写没有 where 的 delete。MySQL 开着安全更新模式时你会收到
ERROR 1175 (HY000): You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column;
没开的时候,你就删光了整张表。靠这条报错当保护不可靠,因为不同环境的 sql_mode 不一样。
三、绝不删生产库。执行前先跑 select @@hostname, database(), current_user();,
把这三个值看一眼再敲回车——我见过有人本地终端连着跳板机,一条 delete 打到了预发库上。
第 1 步,在测试库建上面五张表,插 20 行订单,刻意留 3 行 status 为 null、2 行 pay_time 为 null。
第 2 步,把 3.1 那张表的 9 种条件各跑一遍,把命中行数记下来,确认和你预测的一致;
如果 status <> 20 那行预测错了,说明三值逻辑还没进脑子,回去重读。
第 3 步,给一个订单插两条 pay_status = 20 的支付记录,跑第 8 条对账 SQL 看能不能抓出来;再改成 join 的统计写法,看行数怎么变。
第 4 步,把第 5、6、8、10 条存成一个 .sql 文件,用
mysql -h 10.20.3.31 -uqa_ro -p order_db < check.sql 一次执行,确认输出能直接贴进 bug 单。
这一章的每条陷阱都指向同一个动作——先确认数据长什么样,再判断代码对不对。
null 让「不等于」少返回 188 行,count(字段) 让总数少算 188,
having 和 where 的位置决定你过滤的是行还是组,join 让 12,000 行变成 11,730。
这些不是高级技巧,而是「我的 SQL 到底在问什么」这件基本功。
下一章补上今天刻意回避的事:四种连接各留下什么行,
以及关联条件写在 on 和写在 where 里,为什么结果不一样。