【发布时间】:2015-04-21 06:20:59
【问题描述】:
对于返回相同结果的不同查询,我有两个查询计划 我想知道是否有人可以告诉我哪个“更好”,以及为什么。
SELECT *
FROM bids order by (select ranking from users where users.id = runner_id) DESC limit 1
"Limit (cost=17.62..17.62 rows=1 width=568)"
" -> Sort (cost=17.62..17.62 rows=2 width=568)"
" Sort Key: ((SubPlan 1))"
" -> Seq Scan on bids (cost=0.00..17.61 rows=2 width=568)"
" SubPlan 1"
" -> Index Scan using users_pkey on users (cost=0.28..8.29 rows=1 width=4)"
" Index Cond: (id = bids.runner_id)"
第二个声明和计划:
SELECT "bids".*
FROM "bids" inner join users u on bids.runner_id=u.id ORDER BY u.ranking DESC LIMIT 1
"Limit (cost=17.64..17.64 rows=1 width=572)"
" -> Sort (cost=17.64..17.64 rows=2 width=572)"
" Sort Key: u.ranking"
" -> Nested Loop (cost=0.28..17.63 rows=2 width=572)"
" -> Seq Scan on bids (cost=0.00..1.02 rows=2 width=568)"
" -> Index Scan using users_pkey on users u (cost=0.28..8.29 rows=1 width=8)"
" Index Cond: (id = bids.runner_id)"
【问题讨论】:
-
使用explain.depesz.com从您的解释结果中了解更多信息
-
用
explain analyze运行,你会看到哪个更快 -
嗯,它们确实都花费了相同的时间.. 差别如此之小。
-
第二个有一个嵌套循环,但它所花费的时间被另一个计划中的扫描所花费。
-
这里好像没什么区别。
标签: sql postgresql sql-execution-plan