sql语句查询上万条数据。

来源:百度知道 编辑:UC知道 时间:2024/05/28 04:03:05
select * from pay t where t.txn_dt='20090110' and t.txn_sta_cd='7' and t.ext_user_id not in (select y.ext_user_id from pay y where y.txn_dt='20090110' and y.txn_sta_cd='6')

先说一下这个表 pay 是怎么样的。在这个pay表中一条记录可能的一个属性可能会有两条记录区别这两条记录的值是 y.txn_sta_cd 这个值只能为6或7。7代表失败,6代表成功。

那我的上边那条SQL 语句查询的原理就是如果一条记录有失败的记录还这条失败的记录又在成功状态的记录中那么就不出现就查询结果中。

但是这条语句查询上千条记录时就会非常的慢。可能是我的语句问题,还有没有更好的语句。。

用NOT IN 是很慢的一种查询方式。
试试用Join。

select a.*, 'N' as chk from pay a
where a.txn_dt = '20090110'
and txn_sta_cd = '6'
union
select * from (
select b.*, isnull(c.txn_user_id,'N') as chk
from pay b left outer join pay c
on b.txn_user_id = c.txn_user_id
and b.txn_dt = c.txn_dt
and b.txn_sta_cd = '7'
and c.txn_sta_cd = '6'
where b.txn_dt = '20090110' ) d
where d.chk = 'N'
=========================================
如果不行, 试试下面的

select a.*, 'N' as chk
from pay a
where a.txn_dt = '20090110'
and a.txn_sta_cd = '6'
union
select * from (
select b.*, isnull(c.txn_user_id,'N') as chk
from
(select * from pay
where txn_dt='20090110'
and