PostgreSQL别名子查询返回不存在记录问题求助
问题分析与解决办法
原查询通过直接过滤返回16条目标记录:
SELECT * FROM historical where event_code = 'EMV0727E' and price_level_name = '99'
这段逻辑仅匹配historical表中price_level_name本身为'99'的行。
而改写后的子查询引入了字段转换逻辑:
SELECT ttable.* FROM ( SELECT historical.event_code, historical.datestr, CASE WHEN (historical.price_level_name = '0'::text) THEN '99'::text ELSE historical.price_level_name END AS price_level_name FROM historical ) ttable where ttable.event_code = 'EMV0727E' and ttable.price_level_name = '99'
这里的CASE语句会把原表中所有price_level_name = '0'的行,将该字段值替换为'99'。外层WHERE条件ttable.price_level_name = '99'会同时命中两类数据:
- 原表中
price_level_name为'99'的行 - 原表中
price_level_name为'0'、被CASE语句转为'99'的行
这就是结果多出大量记录的根本原因——新增的记录是原表中event_code = 'EMV0727E'且price_level_name = '0'的数据。
解决方向
- 若仅需原表中
price_level_name = '99'的记录,删除子查询和CASE转换逻辑,直接使用最初的查询即可。 - 若业务需求确实需要将
price_level_name = '0'的行纳入结果,当前查询逻辑是符合预期的,请确认需求是否匹配。 - 关于子查询特性:子查询的行为确实类似临时表,但本次问题并非临时表特性导致,而是你在子查询中修改了字段值,扩大了外层过滤条件的匹配范围。
内容的提问来源于stack exchange,提问作者Jim Murphy
相关产品推荐
相关产品推荐

