【发布时间】:2017-12-09 23:28:39
【问题描述】:
我有这个问题。按帖子的最后评论排序帖子记录。此查询适用于小表。但是,我已经用评论表上大约 2M 行的随机数据填充了数据库。用explain分析查询,发现对Post表执行顺序扫描。
Post.objects.extra(select={'last_update': 'select max(c.create_date) from comment_comment c where c.post_id = post_post.id'}).order_by('-last_update')
我重写了相同的查询,它比当前的查询要快。但我找不到适合 django 的 orm 查询的方法。我该如何重写它?如果可能的话,我想尽可能不使用原始查询来编写它。
问候。谢谢你的帮助。
select
p.*,
t.last_update
from
post_post p
join
( select c.post_id as pid, max(c.create_date) as last_update from comment_comment c group by pid) t
on p.id = t.pid
order by t.last_update desc
limit 50;
【问题讨论】:
标签: django postgresql orm