テーブルを質問用と回答用の 2 つの異なるテーブルに分割することをお勧めします。
ただし、必要なクエリは次のように記述できます。
SELECT posts.*
FROM
posts INNER JOIN
(SELECT IF(ref_post_id=0,post_id,ref_post_id) as id, Max(Date) as maxdate
FROM posts
GROUP BY id) p
ON
(p.maxdate = posts.date) AND
(p.id =IF(posts.ref_post_id=0,posts.post_id,posts.ref_post_id))
すべての質問/回答の最大日付を選択するには、 でグループ化する必要があります。ただし、 でグループ化する必要がref_post_id
ある場合を除き、したがって IF.ref_post_id = 0
post_id
サブクエリを使用して posts テーブルをそれ自体と結合するときは、同じトリックを使用する必要があります。
編集:質問を削除済みとしてマークする必要がある場合は、削除されたすべての質問と回答を上記の選択から削除する必要があり、削除されていない質問のみを選択するには、もう 1 つのサブクエリを使用する必要があります。
SELECT posts.*
FROM
posts INNER JOIN
(SELECT IF(ref_post_id=0,post_id,ref_post_id) as id, Max(Date) as maxdate
FROM posts
WHERE EXISTS (SELECT null
FROM posts posts_sub
WHERE
posts_sub.post_id =
IF(posts.ref_post_id=0,posts.post_id,posts.ref_post_id)
AND posts_sub.deleted =0)
GROUP BY id) p
ON
(p.maxdate = posts.date) AND
(p.id =IF(posts.ref_post_id=0,posts.post_id,posts.ref_post_id))