当前位置: 代码迷 >> Java Web开发 >> 一个蛋疼的sql,性能怎么优化?
  详细解决方案

一个蛋疼的sql,性能怎么优化?

热度:8968   发布时间:2013-02-25 21:14:08.0
一个蛋疼的sql,性能如何优化??
具体的sql就不写了, 太长了,

需求是这样的:
   
  一个历史表 里面几个关键的字段 一个主键id 公司标识copmanyid 一个成功或失败状态 status 一个createtime 需求很简单  

现在要查询下面的数据:
  1 如果 某公司只有一条历史记录,则显示状态为失败的、
  2 如果 公司有多条记录,只要有一条是成功的就不显示,如果都为失败的,则显示最新及最近的一条


我的思路是这样的 在java程序中作判断 然后拼接sql, 多条记录union 一条记录,一条记录的好搞,主要是多条记录的,首先查出多条记录并且全部为失败的公司标识,然后没查出一个公司标识就union一次, 结果表里数据很多,union了几十次,直接卡死,


哪位大侠给个指点 ,实在想不出好的方法了,在sql优化或者在java程序中处理都可以!!!!

分不多了,全部献上...

我知道我发的地方不太对,可是发在oracle没人......
大家帮帮忙吧

------解决方案--------------------------------------------------------
做过类似的,开始也用union ,但是性能实在不怎么样。。。。。
你可以试试循环公司,一个公司一个公司的取数据,虽然要连多次DB,但是性能上会好很多,至少不会被卡死
------解决方案--------------------------------------------------------
坐等大牛。
------解决方案--------------------------------------------------------
我的思路是这样的 在java程序中作判断 然后拼接所有ID 到数组中,最后用 select * from history_table where id in id_ARRAY.
------解决方案--------------------------------------------------------
我觉得吧,这个逻辑真够复杂.上策是把这逻辑改了.

例如:直接新搞一个表,就记录公司名,是否失败2个字段.然后程序在适当的时候直接去修改这个表.这查询就不用说了
------解决方案--------------------------------------------------------
for example
SQL code
select a.id, a.copmanyid, '失败' as status, a.createtime  from yourtable a where not exists (select 1 from yourtable                     where copmanyid = a.copmanyid and id != a.id) --只存在一条记录    or (a.createtime = (select max(createtime) from yourtable                          where copmanyid = a.copmanyid) --最近一条记录        and not exists (select 1 from yourtable                         where copmanyid = a.copmanyid                           and status = '成功') --不存在成功记录       )
------解决方案--------------------------------------------------------
SQL code
select t.id,t.companyid, '失败' as status,t.createtime from yourtable t    where not exists (select 1 from yourtable t1 where t1.companyid = t.companyid and t1.id!=t.id)union allselect t.id,t.companyid, '失败' as status,t.createtime from yourtable t    where t.createtime = (select max(createtime) from yourtable t1 where t1.companyid=t.companyid)    and not exists (select 1 from yourtable t2 where t2.companyid=t.companyid and status='成功')
------解决方案--------------------------------------------------------
select a.id, a.copmanyid, '失败' as status, a.createtime
from yourtable a
 where not exists (select 1 from yourtable 
where copmanyid = a.copmanyid and id != a.id) --只存在一条记录
or (a.createtime = (select max(createtime) from yourtable 
where copmanyid = a.copmanyid) --最近一条记录
and not exists (select 1 from yourtable
where copmanyid = a.copmanyid
and status = '成功') --不存在成功记录
)

那位大神能给解释一下语句中的:select a.id, a.copmanyid, '失败' as status, a.createtime
from yourtable a。'失败' as status,红色的字段是什么意思?目的是什么?
------解决方案--------------------------------------------------------
'失败' as status 就是把两个汉字直接当作字段值进行返回,仅此而已。

比如:

select 'Hello' as xx, 'World' as oo from dual;

查询出来的结果就是两个字段,字段1是xx,字段2是oo
  相关解决方案