编写SQL查询筛选test_t1表中列值存在差异的client_id
解决方案:找出存在字段不一致的client_id
针对你的需求,要从test_t1表中筛选出同一client_id下存在不同client_code或emp_ref_code的记录,以下提供两种常用实现方式:
方法1:GROUP BY + HAVING(逻辑清晰,推荐)
通过分组后统计唯一值数量判断不一致:
SELECT client_id FROM test_t1 GROUP BY client_id HAVING COUNT(DISTINCT client_code) > 1 OR COUNT(DISTINCT emp_ref_code) > 1;
说明:
COUNT(DISTINCT 列名)统计分组内该列的唯一值总数- 当
client_code唯一值数>1,说明同一client_id下存在不同编码;同理判断emp_ref_code - 满足任意一个条件的
client_id会被返回
方法2:自连接查询(适合大表性能优化)
通过自连接对比同一client_id下的不同行:
SELECT DISTINCT t1.client_id FROM test_t1 t1 JOIN test_t1 t2 ON t1.client_id = t2.client_id WHERE (t1.client_code != t2.client_code OR t1.emp_ref_code != t2.emp_ref_code) AND t1.seq_id != t2.seq_id; -- 排除与自身行的无意义对比
说明:
DISTINCT确保每个client_id仅返回一次- 若字段存在
NULL值,需替换不等判断为兼容NULL的逻辑:
通用兼容写法:
部分数据库(如PostgreSQL)支持更简洁的语法:WHERE ( (t1.client_code != t2.client_code OR (t1.client_code IS NULL) != (t2.client_code IS NULL)) OR (t1.emp_ref_code != t2.emp_ref_code OR (t1.emp_ref_code IS NULL) != (t2.emp_ref_code IS NULL)) ) AND t1.seq_id != t2.seq_id;WHERE (t1.client_code IS DISTINCT FROM t2.client_code OR t1.emp_ref_code IS DISTINCT FROM t2.emp_ref_code) AND t1.seq_id != t2.seq_id;
内容的提问来源于stack exchange,提问作者Node98
相关产品推荐
相关产品推荐

