0

我的 django 应用程序中有模型,它们具有发布/回复关系,并试图按他们最新回复的时间对帖子进行排序,或者,如果没有回复,他们自己的时间戳。这就是我现在所拥有的:

threads = ConversationThread.objects.extra(select={'sort_date':
                                    """select case when (select count(*) from conversation_conversationpost 
                                    where conversation_conversationpost.thread_id = conversation_conversationthread.id) > 0 
                                    then (select max(conversation_conversationpost.post_date) 
                                    from conversation_conversationpost where conversation_conversationpost.thread_id = conversation_conversationthread.id) 
                                    else conversation_conversationthread.post_date end"""}).order_by('-sort_date')

虽然它有效,但我有一种预感,这不是最简洁或最有效的方法。有什么更好的方法?

4

2 回答 2

0
SELECT  *,
        (
        SELECT  COALESCE(MAX(cp.post_date), ct.post_date)
        FROM    conversation_conversationpost cp
        WHERE   cp.thread_id = ct.id
        ) AS sort_date
FROM    conversation_conversationthread ct
ORDER BY
        sort_date DESC
于 2013-01-17T22:02:10.377 回答
0

众所周知,相关的子查询速度很慢。
ALEFT JOIN可能要快得多(取决于数据分布):

SELECT  t.*, COALESCE(p.max_post_date, t.post_date) AS sort_date
FROM    conversation_conversationthread t
LEFT    JOIN (
    SELECT thread_id, MAX(post_date) AS max_post_date
    FROM   conversation_conversationpost
    GROUP  BY thread_id
    ) p ON p.thread_id = t.id
ORDER   BY sort_date DESC;
于 2013-01-18T01:31:46.807 回答