如何在隐式游标中获取仅含一条'inf'记录的表列值
解决方案
要实现你的需求,核心是先从articles_type表中筛选出符合条件的code,再关联articles_description表获取数据,直接修改游标SQL即可,不需要额外函数:
正确的游标写法
cursor c_cur is select a.* from articles_description a where a.code in ( -- 子查询筛选出仅含1条'inf'记录的code(对应示例中的2和3) select b.code from articles_type b group by b.code having count(*) = 1 -- 该code只有1条记录 and max(b.value) = 'inf' -- 这条记录的value是'inf' );
或者用JOIN写法,逻辑完全一致:
cursor c_cur is select a.* from articles_description a inner join ( select code from articles_type group by code having count(*) = 1 and max(value) = 'inf' ) b on a.code = b.code;
原写法的问题
原SQL只是关联了所有含'inf'的记录,但没过滤掉像code=1这种既有'inf'又有其他值的情况。通过子查询先按code分组,再用having子句同时限制记录总数为1且唯一的记录值是'inf',就能精准筛选出你要的code。
扩展说明
如果你的需求是只要code对应的'inf'记录数为1,不管有没有其他非'inf'记录(这种情况会包含像code=1这类有1条'inf'+多条其他值的code,不符合你给出的示例结果,仅作参考),可以把子查询改成:
select b.code from articles_type b where b.value = 'inf' group by b.code having count(*) = 1
内容的提问来源于stack exchange,提问作者reymagnus
相关产品推荐
相关产品推荐

