Postgres: Why is the performance so bad on subselects with Offset/Limit

后端 未结 2 1647
梦谈多话
梦谈多话 2021-01-20 06:38

Can you please help me understand the reason for the performance drop between these statements?

For me it seems like in case of D & E he is first joining the add

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-20 06:41

    I think that the join expressed in the SELECT clause is being executed even for the 100000 rows you are not including in the final data set.

    How about this:

    SELECT s2.user_id,
    (SELECT address_id FROM address a WHERE a.user_id = s2.user_id ORDER BY address_id OFFSET 0 LIMIT 1) AS a_id
    FROM (select *
          from   subscribers s
          ORDER BY s.user_id
          OFFSET 100000 LIMIT 200) s2
    

    Failing that, try a common table expression:

    With s2 as (
      select *
      from   subscribers s
      ORDER BY s.user_id
      OFFSET 100000 LIMIT 200)
    SELECT s2.user_id,
    (SELECT address_id FROM address a WHERE a.user_id = s2.user_id ORDER BY address_id OFFSET 0 LIMIT 1) AS a_id
    FROM s2
    

提交回复
热议问题