0

我有一个名为sales以下几列的表:

salesno (PK, char(25))
advanceno (char(15), not null)

现在我想选择所有salesno不在的行advanceno

SELECT salesno 
FROM sales 
WHERE salesno NOT IN (SELECT advanceno FROM sales)

查询很慢,因为 sales 表有数十万行。

我这样做了,而且速度非常快:

SELECT salesno 
FROM sales 
WHERE salesno NOT IN ('000008360', '000008361', '000008362', '000008363', '000008364')

如何优化查询?

4

1 回答 1

4

试试这个:

DECLARE @sales as Table (salesno char(25)
,advanceno char(15) not null)

INSERT INTO @sales(salesno,advanceno)
SELECT '000008360','000008360' UNION ALL
SELECT '000008361','000008362' UNION ALL
SELECT '000008362','000008364' 

SELECT  s.salesno 
FROM    @sales s 
LEFT JOIN @sales a ON a.advanceno = s.salesno
WHERE   a.advanceno IS NULL

在你的例子中,试试这个

SELECT  s.salesno 
FROM    sales s 
LEFT JOIN sales a ON a.advanceno = s.salesno
WHERE   a.advanceno IS NULL
于 2012-05-08T03:36:20.363 回答