我想知道通过在字段中使用子查询或连接哪个查询的性能会更好。
例如,我有两个表格书和作者(它们之间的一对多关系作为作者1->*书(。
Sub Query in field (fetching author name using subquery):
select
b.book_id,
b.book_name,
b.author_id,
(select author_name from author where author.id=b.author_id as author_name
from book b
Join Query (fetching author name by joining book & author tables):
select
b.book_id,
b.book_name,
b.author_id,
a.author_name
from book b inner join author a on b.author_id = a.author_id
我正在使用 Postgres DB,如果我检查查询计划,那么 join 正在执行嵌套循环,而子查询仅使用 PK author_id。我在author_id列上有索引。
它们做不同的事情。 第一个查询的等效项是左联接,而不是内部联接。 然后,只有当您可以保证author
永远不会有多个匹配项时,它们才是等效的。
此外,如果author
为给定author_id
返回多行,则第一个将返回错误。
因此,您应该使用可以执行所需操作的版本。
也就是说,如果您有两个等效版本的查询(使用left join
(,那么执行计划应该非常相似。 特别是,两者都将利用authors(author_id)
指数 - 从性能的角度来看,这是您真正关心的。