2013-01-17 47 views
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') 

雖然它的作品,我有一種預感,這是不是這樣做的最簡潔和有效的方式。什麼會更好?

回答

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 
+0

謝謝,成功了!它沒有爲速度做任何事情,但至少代碼更易於維護。 – Tiki

0

Correlated subqueries是臭名昭着的緩慢。
一個LEFT 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;