Oracle 中对clob字段进行distinct 操作

oracle 10+g不支持对类型为CLOB的列进行distinct,也不支持union,所以在遇到此问题,需要对SQL语句进行重新,从另一思想去实现同样的效果的。union没仔细思考过,具体还要看union里面的条件如何,最简单的方法是利用to_char将clob字段转换成char型,但存在一个问题,如clob中的字符长度超过4000时会报错。在此主要对distinct的转换方法进行列举: 

表结构如下: 

Table1: 


id(varchar)  title(varchar)  content(clob) 
1  title1  <CLOB> 
2  title2  <CLOB> 


Table2: 


id(varchar)  table_id(varchar)  object(varchar) 
1  1  123 
2  1  abc 
3  1  111 
4  1  222 
5  2  123 




SQL语句: 

select distinct table1.* from table2 table2 left join table1 table1 on table1.id = talbe2.table_id 

where table2.object = '123' or table2.object = '111' or table2.object = '222' or table2.object = '333' 

执行该语句,出现错误:ORA-00932,数据类型不一致:应为-,却获得CLOB。 




1、利用rowid,过滤重复的数据。 

这个方法的思路来源,就是对某个字段进行distinct时的解决方法。 

基本思路:select   B.name,B.id   from   table   B   where     not   exists   (select   1   from   table   A     where   A.name   =   B.name   AND   B.id_key   >   A.id_key) 

A表,B表为同一张表,表中的数据存在name相同的,但id_key不同,该语句的目的是把同名的只显示一条即可,其它同名记录过滤。 

将该思想转换到当前的问题上,利用每条记录的rowid不同进行过滤。 

select p4.*, p4.rowid from ( 
select p.* from table2 s left join table1 p on s.table_id = p.id 
where s1.object = '123' or s1.object = '111' or s1.object = '222' or s1.object = '333' 
) p4 
where not exists ( 
select 1, p2.rowid from ( 
select p1.* from table2 s1 left join table1 p1 on s1.table_id= p1.id 
where s1.object = '123' or s1.object = '111' or s1.object = '222' or s1.object = '333') p2 
where p4.id = p2.id and p4.rowid > p2.rowid 


2、采用子查询进行过滤重复的数据。 

select * from table1 t1 where t1.id in ( 

selcet distinct p1.id from table2 s1 left join table1 p1 on s1.table_id= p1.id 
      where s1.object = '123' or s1.object = '111' or s1.object = '222' or s1.object = '333' 



3、采用to_char函数,直接使用distinct(前提是:clob字段中的字符长度少于4000)。 

select distinct table1.id, table1.tittle, to_char(table1.content) from table2 table2 

        left join table1 table1 on table1.id =  talbe2.table_id 

        where table2.object = '123' or table2.object = '111' or table2.object = '222' or table2.object = '333

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Oracle查询含有CLOB字段慢的问题主要原因是CLOB字段的特性决定了其存储方式和查询性能。CLOB字段存储的是大文本数据,其在数据库以存放在不同的页,而非在表直接存储,这导致在查询时需要从多个页读取数据,从而增加了查询的时间。 另一个可能的原因是查询语句CLOB字段进行了全表扫描或者模糊查询的操作。全表扫描将导致查询所有的数据行,而模糊查询则需要对每一条记录进行匹配,这些操作都会增加查询的时间。 解决这个问题的方法有以下几种: 1. 创建适当的索引:对于经常查询的CLOB字段,可以创建全文索引或者函数索引,这样可以加快查询速度。 2. 使用子查询:如果查询结果不需要包含CLOB字段,可以将CLOB字段的查询放置在子查询,然后在主查询引用子查询的结果。这样可以减少查询CLOB字段的开销。 3. 优化查询语句:尽量避免使用全表扫描和模糊查询等低效操作,可以根据具体需求优化查询语句,减少查询CLOB字段的次数和范围。 4. 使用分页查询:如果查询结果仅需要部分记录,可以使用分页查询的方式,每次只查询指定页的记录,这样可以减少读取CLOB字段的数据量。 最后,如果以上方法仍然不能解决查询慢的问题,还可以考虑增加服务器的硬件资源,如增加内存或者更快的存储设备,以提高查询性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值