使用DISTINCT正确连接多个表

时间:2013-05-20 14:24:22

标签: sql join distinct

SELECT * FROM f_posts 
INNER JOIN f_topics 
ON f_posts.post_topic=f_topics.topic_id
INNER JOIN f_subcategories
ON f_subcategories.scat_id=f_topics.topic_scat
ORDER BY f_posts.post_date
DESC LIMIT 0,3

我想列出前3个结果,由于最后3个评论都在同一个主题中,我得到了相同的主题3次。 Nor DISTINCT和GROUP BY似乎也不起作用。

1 个答案:

答案 0 :(得分:1)

尝试:

SELECT p.* , t.*, s.*
FROM f_posts p
INNER JOIN (select post_topic, max(post_date) max_date
            from f_posts
            group by post_topic
            order by max_date desc LIMIT 0,3) m
        ON p.post_topic = m.post_topic and p.post_date = m.max_date
INNER JOIN f_topics t ON p.post_topic=t.topic_id
INNER JOIN f_subcategories s ON s.scat_id=t.topic_scat
ORDER BY f_posts.post_date DESC