一、有这样一张表,如下
temp:
id name address
1 福州市汽车站 五四路
2 福州市汽车站北站 五四路
3 福州市汽车站售票处 五四路
4 公厕 六一路
5 公厕 六一路
6 公厕 六一路
二、说明
如何实现自身表的不重复查询,我自己写了一个程序块如下:
declare
2 Cursor poiCur is select * from temp;
3 poirow temp%rowtype;
4 i integer;
5 begin
6 Open poiCur;
7 loop
8 Fetch poiCur into poirow;
9 select count(*) into i from temp where name like '%'||poirow.name||'%' and address=poirow.address;
10 if i>1 then
11 Dbms_Output.put_line('找到名称为:'||poirow.name||' 的数据,一共有:'||i||' 条
。');
12 end if;
13 Exit when poiCur%notFound;
14 End loop;
15 Close poiCur;
16 End;
结果是:
找到名称为:福州市汽车站 的数据,一共有:3 条
找到名称为:公厕 的数据,一共有:3 条
找到名称为:公厕 的数据,一共有:3 条
找到名称为:公厕 的数据,一共有:3 条三、问题
(1)查询"福州市汽车站"时的问题不大,但是当查询到“公厕”时,因为字段完全一样时就出现了重复,有没有办法的得不重复的结果?
(2)有没有更好的解决类似查询一张表中重复的数据,不一定时完全重复,也有可能时大部分重复,就像“福州市汽车站”这种情况?
temp:
id name address
1 福州市汽车站 五四路
2 福州市汽车站北站 五四路
3 福州市汽车站售票处 五四路
4 公厕 六一路
5 公厕 六一路
6 公厕 六一路
二、说明
如何实现自身表的不重复查询,我自己写了一个程序块如下:
declare
2 Cursor poiCur is select * from temp;
3 poirow temp%rowtype;
4 i integer;
5 begin
6 Open poiCur;
7 loop
8 Fetch poiCur into poirow;
9 select count(*) into i from temp where name like '%'||poirow.name||'%' and address=poirow.address;
10 if i>1 then
11 Dbms_Output.put_line('找到名称为:'||poirow.name||' 的数据,一共有:'||i||' 条
。');
12 end if;
13 Exit when poiCur%notFound;
14 End loop;
15 Close poiCur;
16 End;
结果是:
找到名称为:福州市汽车站 的数据,一共有:3 条
找到名称为:公厕 的数据,一共有:3 条
找到名称为:公厕 的数据,一共有:3 条
找到名称为:公厕 的数据,一共有:3 条三、问题
(1)查询"福州市汽车站"时的问题不大,但是当查询到“公厕”时,因为字段完全一样时就出现了重复,有没有办法的得不重复的结果?
(2)有没有更好的解决类似查询一张表中重复的数据,不一定时完全重复,也有可能时大部分重复,就像“福州市汽车站”这种情况?
if i>1 then 给屏蔽掉了,否则会输出:
找到名称为:福州市汽车站北站 的数据,一共有:1 条
找到名称为:福州市汽车站售票处 的数据,一共有:1 条
初步判断,你不应该使用loop和if。
declare
Cursor poiCur is select addres,min(name) as min_name from temp group by addres;
poirow temp%rowtype;
i integer;
begin
Open poiCur;
loop
Fetch poiCur into poirow;
select count(*) into i from temp where name like '%'||poirow.min_name||'%' and address=poirow.address;
Dbms_Output.put_line('找到名称为:'||poirow.min_name||' 的数据,一共有:'||i||' 条。'); Exit when poiCur%notFound;
End loop;
Close poiCur;
End;
select addres,min(name) as min_name from temp group by addres;
这个查询语句会导致结果不准确,
因为例如:表中有两个数据,name不同,但是address却相同,这样的话就会屏蔽name大的那个字段,而这两个字段并不是属于重复的。
1 福州市汽车站 五四路
2 福州市汽车站北站 五四路
3 福州市汽车站公厕 五四路
4 公厕 六一路
addres,min(name)范围剔除,之后再循环往复,直至记录=0。找高手吧!否则建议不要用存储过程了,后台代码实现判断还是比较好!