【问题标题】:Which query plan is faster/better哪个查询计划更快/更好
【发布时间】: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


【解决方案1】:

它不足以产生任何真正的改变。我会使用第二个,因为第一个具有相当不规则的语法,这使得它更难以维护。略。

你也可以试试这个:

select b.*
from   (select   id
        from     users
        order by ranking desc
        limit    1) u
join   bids                b on b.runner_id = u.id
limit  1

最后一个限制 1 可能是多余的。

【讨论】:

    【解决方案2】:

    我认为这个查询性能比第二个更好

    SELECT * 
    FROM bids order by (select ranking from users where users.id = runner_id) DESC limit 1;
    

    因为在第二个中看到了解释分析器平面差异

    嵌套循环(成本=0.28..17.63 行=2 宽度=572)

    在数据结构方面总是循环使得程序输出的复杂度更高。还有很多其他参数,请参阅

    宽度 两种情况的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2014-09-18
      • 2017-02-18
      • 2011-03-09
      • 1970-01-01
      相关资源
      最近更新 更多