sql - 尝试优化嵌套的 PostgreSQL WHERE IN

标签 sql postgresql postgresql-performance

我有一个类似于以下内容的 Postgres (9.1) 客户数据库:

customers.id
customers.lastname
customers.firstname

invoices.id
invoices.customerid
invoices.total

invoicelines.id
invoicelines.invoiceid
invoicelines.itemcode
invoicelines.price

我构建了一个搜索,其中列出了购买了特定商品(例如“abc”)的所有客户。

Select * from customers WHERE customers.id IN
    (Select invoices.customerid FROM invoices WHERE invoices.id IN
        (Select invoicelines.invoiceid FROM invoicelines WHERE
        invoicelines.itemcode = 'abc')
    )

搜索工作正常并找到正确的客户,但在包含 200 万张发票和 200 万行项目的数据库上大约需要 10 秒左右。

我想知道是否有另一种方法可以稍微减少一点。

最佳答案

另一种方法是使用 EXISTS:

Select * 
from customers 
WHERE EXISTS (
   Select invoices.customerid 
   FROM invoices 
   JOIN invoicelines
      ON invoicelines.invoiceid = invoices.id AND
         invoicelines.itemcode = 'abc' AND
         customers.id = invoices.customerid)

关于sql - 尝试优化嵌套的 PostgreSQL WHERE IN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35700292/

相关文章:

sql - 用于高容量的 rrd 工具替代品

postgresql - 将字符串作为文本发送到函数 POSTGRESQL

mysql - 使用 SQL 计算组合

脚本中的Mysql数据库错误

sql - postgreSQL 斐波那契数列 - 查询没有结果数据的目的地

django - 如何防止此 PostgreSQL 查询中的全表扫描?

postgresql - Alter Table Set Statistics 需要表锁

postgresql - 多对多表 - 性能很差

mysql - 在主查询中使用子查询

postgresql - 使列可为空会锁定表以进行读取吗?