You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:20:27