如何用SQL检查子表与父表指定列值一致性并找出异常行
解决方案
假设父表名为parent_table,包含主键parent_id和交易类型列transaction_type;子表名为child_table,包含主键child_id、关联父表的外键parent_id以及交易类型列transaction_type。
基础查询(不处理NULL场景)
以下SQL可直接筛选出子表中交易类型与对应父表不一致的异常行:
SELECT c.child_id AS 异常子表行ID, c.parent_id AS 对应父表行ID FROM child_table c INNER JOIN parent_table p ON c.parent_id = p.parent_id WHERE c.transaction_type != p.transaction_type;
兼容NULL的查询
如果交易类型列可能存在NULL值(NULL与任何值比较结果都不为真),需要补充判断逻辑:
SELECT c.child_id AS 异常子表行ID, c.parent_id AS 对应父表行ID FROM child_table c INNER JOIN parent_table p ON c.parent_id = p.parent_id WHERE c.transaction_type <> p.transaction_type OR (c.transaction_type IS NULL AND p.transaction_type IS NOT NULL) OR (c.transaction_type IS NOT NULL AND p.transaction_type IS NULL);
逻辑说明
- 通过
INNER JOIN根据外键parent_id关联父表与子表,确保只处理存在对应父表记录的子表行 WHERE子句精准筛选交易类型不匹配的情况,兼容基础场景和含NULL的特殊场景- 查询结果直接返回异常子表的ID以及对应的父表ID,便于定位和修正错误数据
内容的提问来源于stack exchange,提问作者elector
相关产品推荐
相关产品推荐

