以下两个查询返回相同的信息;但是,第一个需要 1.1 秒才能完成,第二个需要 0.06 秒。
此表有198,810 条记录并"Contacts"."ReqID"
已编入索引。
- 为什么我看到(看似)不太复杂的查询对性能造成了如此大的影响?
- 为什么 UNION 子查询会加快这个过程?
*编辑*
我已经快速连续地运行了两个查询,并且没有看到性能变化。
查询 1
SELECT
"Contacts"."ContactID",
"Contacts"."ReqID"
FROM
"Contacts"
WHERE
"Contacts"."ReqID" = 2426;
*编辑*
解释分析
Index Scan using "Contacts_ReqID_idx" on "Contacts" (cost=0.00..30.08 rows=11 width=78) (actual time=0.076..0.115 rows=14 loops=1)
Index Cond: ("ReqID" = 2426)
Total runtime: 0.159 ms
1.1秒返回14条记录。
查询 2
SELECT
"T1"."ContactID",
"T1"."ReqID"
FROM
(
SELECT
"Contacts"."ContactID",
"Contacts"."ReqID"
FROM
"Contacts"
WHERE
"Contacts"."ReqID" = 2426
UNION
SELECT
"Contacts"."ContactID",
"Contacts"."ReqID"
FROM
"Contacts"
WHERE
"Contacts"."ReqID" = 2426
) AS "T1"
ORDER BY
"ReqID"
*编辑*
解释分析
Sort (cost=61.74..61.80 rows=22 width=100) (actual time=0.313..0.329 rows=14 loops=1)
Sort Key: "Contacts"."ReqID"
Sort Method: quicksort Memory: 26kB
-> HashAggregate (cost=60.81..61.03 rows=22 width=78) (actual time=0.266..0.285 rows=14 loops=1)
-> Append (cost=0.00..60.37 rows=22 width=78) (actual time=0.063..0.201 rows=28 loops=1)
-> Index Scan using "Contacts_ReqID_idx" on "Contacts" (cost=0.00..30.08 rows=11 width=78) (actual time=0.059..0.106 rows=14 loops=1)
Index Cond: ("ReqID" = 2426)
-> Index Scan using "Contacts_ReqID_idx" on "Contacts" (cost=0.00..30.08 rows=11 width=78) (actual time=0.006..0.024 rows=14 loops=1)
Index Cond: ("ReqID" = 2426)
Total runtime: 0.410 ms
0.06 秒返回14 条记录。