我们的应用已暂时使用此查询:
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行。这不是左外连接的有效用法吗?
重写此查询的更好方法是什么?
谢谢!
答案 0 :(得分: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
答案 1 :(得分:0)
最好的方法是这个
SELECT id
FROM invoice as i
WHERE not exists
(SELECT invoice_id FROM invoice_transaction as it where it.invoice_id=i.id )