1

我们的应用程序使用这个查询已经有一段时间了:

SELECT id 
FROM invoice 
WHERE id NOT IN 
(SELECT invoice_id FROM invoice_transaction) 

#437 rows returned

在代码审查中,这个查询用左外连接重写:

SELECT invoice.id 
FROM invoice 
LEFT OUTER JOIN invoice_transaction on invoice.id=invoice_transaction.invoice_id 

#586 rows returned

第一个查询返回 437 行,第二个(假定相同)查询返回 586 行。这不是对左外连接的有效使用吗?

重写此查询的更好方法是什么?

谢谢!

4

2 回答 2

4

以下查询应返回与第一个查询相同的结果:

SELECT invoice.id 
FROM invoice 
LEFT OUTER JOIN invoice_transaction 
             on invoice.id = invoice_transaction.invoice_id
WHERE invoice_transaction.invoice_id IS NULL
于 2012-11-05T23:52:27.167 回答
0

最好的方法是这个

SELECT id 
FROM invoice as i
WHERE not exists
(SELECT invoice_id FROM invoice_transaction as it where it.invoice_id=i.id ) 
于 2012-11-06T00:12:55.120 回答