我的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 :(得分: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
答案 1 :(得分:0)
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;