优化SQL查询,需要建议

我在SQL Server中有一个包含4列的表:

Invoice No,Date,Amt and ID

我必须找到具有相同发票编号,日期和金额但ID不同的发票。 我正在通过自连接填充结果,但似乎这不是获取结果的优化方法。

我的查询:

select * from table t1 join 
table t2 on t1.invoice = t2.invoice 
where t1.invoice=t2.invoice and t1.amount=t2.amount and t1.date =t2.date and t1.id!=t2.id

请给我建议一种获取正确结果的优化方法。

aa1123128 回答:优化SQL查询,需要建议

尝试一下。使用左联接并过滤这些空值。

select * from (
    select t1.invoiceno,t1.date,t1.amt,t1.id,t2.id as t2ID
    from invoices t1
    left join invoices t2 on t2.invoiceno = t1.invoiceno 
        and t2.date = t1.date 
        and t2.amt = t1.amt
        and t2.id != t1.id) t3 
where coalesce(t3.t2ID,0) != 0
,

您可以使用索引来加快从大型数据库的检索。 使用子查询,但不要仅使用子查询来显示一列。

我建议使用子查询作为新表来使用联接。 就像第一个答案一样。

,

不存在

select t1.* from table t1 
where not exists( select 1 form 
table t2 where t1.invoice = t2.invoice 
and t1.invoice=t2.invoice and t1.amount=t2.amount 
and t1.date =t2.date and   t1.id=t2.id
having count(*)>1
)
,
  

必须找到具有相同发票编号,日期和金额但ID不同的发票。

使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.Invoice = t.invoice and
                    t2.Date = t.date and
                    t2.amount = t.amount and
                    t2.id <> t.id
             )
order by t.invoiceNo,t.date,t.amount,t.id;

这将在相邻行上显示匹配的发票。为了提高性能,您需要在(invoice,date,amount,id)上建立索引。

如果您只想在发生这种情况的三胞胎,可以使用聚合:

select invoice,min(id),max(id)
from t
group by invoice,amount
having count(distinct id) > 1;

注意:如果重复项超过两个,则仅显示两个ID。

本文链接:https://www.f2er.com/3168656.html

大家都在问