我有一个Postgres表,其中有超过800万行。给出以下两种通过 DBD :: Pg 进行相同查询的方式,我得到的结果截然不同。
I have a Postgres table with more than 8 million rows. Given the following two ways of doing the same query via DBD::Pg, I get wildly different results.
$q .= '%'; ## query 1 my $sql = qq{ SELECT a, b, c FROM t WHERE Lower( a ) LIKE '$q' }; my $sth1 = $dbh->prepare($sql); $sth1->execute(); ## query 2 my $sth2 = $dbh->prepare(qq{ SELECT a, b, c FROM t WHERE Lower( a ) LIKE ? }); $sth2->execute($q);查询2至少比查询1慢一个数量级...似乎不是使用索引,而查询1使用索引。
query 2 is at least an order of magnitude slower than query 1... seems like it is not using the indexes, while query 1 is using the index.
请问为什么。
推荐答案带有 Like 表达式的b树索引只能在搜索模式为左锚的情况下使用,即以% 。 手册中的更多详细信息。 感谢@evil otto提供的链接。此链接指向当前版本。
With LIKE expressions, b-tree indexes can only be used if the search pattern is left-anchored, i.e. terminated with %. More details in the manual. Thanks to @evil otto for the link. This link to the current version.
您的第一个查询在准备时会提供此基本信息,因此查询计划者可以使用匹配的索引。
Your first query provides this essential information at prepare time, so the query planner can use a matching index.
您的第二个查询在准备时没有提供有关模式的任何信息,因此查询计划者无法使用任何索引。
Your second query does not provide any information about the pattern at prepare time, so the query planner cannot use any indexes.