我怎样才能提高这个 SQL 查询性能?

How can I improve this SQL query performace?

我有如下所示的查询。我对查询进行了“EXPLAIN ANALYZE”以查看查询性能中的瓶颈,而 JOINS 是罪魁祸首。

我对 table 结构进行了简要描述,以便更好地理解。 tables 本身无法更改。

table ai {
   a_id foreign_key
   i_id foreign_key
} 
table a {
   id
   c_id foreign_key
}
table i {
   id
   value
}
table c {
   name
   begin_time
   id
}

这是 SQL 查询。

SELECT
  DISTINCT ON (c.begin_time, c.id)
  c.id,
  c.name,
  c.begin_time
FROM
  ai
  INNER JOIN i ON (
    ai.i_id = i.id
  )
  INNER JOIN a ON (
    ai.a_id = a.id
  )
  INNER JOIN container ON (
    a.c_id = c.id
  )
WHERE
  i.value = 'a.b.c.d'
ORDER BY
  c.begin_time DESC
  

我不擅长 SQL 查询。我想知道是否可以更改查询本身以提高性能。

  • 您的主查询只需要 c table
  • ,其他table只需要判断最终结果是否需要c记录
  • (if) c table 不包含重复项:不再需要 DISTINCT。

简化查询:


SELECT
  c.id, c.name, c.begin_time
FROM c
WHERE EXISTS (
        SELECT * FROM ai
        JOIN i ON ai.i_id = i.id AND i.value = 'a.b.c.d'
        JOIN a ON ai.a_id = a.id
        WHERE  a.c_id = c.id
        )
ORDER BY c.begin_time DESC
        ;