从主题中选择最后5个帖子?

时间:2015-03-19 11:36:07

标签: php mysql posts

您好我正在尝试选择发布帖子的最后五个主题。 我认为这个问题本来有用,但如果有人可以帮我解决的话,我真的会被困在这个问题上。 $query = yasDB_select("SELECT * FROM forumposts INNER JOIN forumtopics ON forumposts.id=forumtopics.id ORDER by forumposts.date DESC limit 5");

1 个答案:

答案 0 :(得分:1)

我认识到您的查询存在一些问题。

正确的解决方案:

SELECT DISTINCT(forumtopics.name)
FROM forumtopics LEFT JOIN forumposts ON forumposts.topicid = forumtopics.id
ORDER BY forumposts.id DESC LIMIT 5;

如果您对有关主题的更复杂数据感兴趣,可以执行以下操作:

SELECT * FROM (SELECT DISTINCT(forumtopics.id) FROM forumtopics LEFT
JOIN forumposts  ON forumposts.topicid = forumtopics.id ) topics  LEFT
JOIN forumtopics ON topics.id = forumtopics.id ORDER BY topics.id DESC
LIMIT 5 ;

我使用了以下测试模式:

CREATE TABLE forumposts (   id int,   topicid int,   content text ); 
CREATE TABLE forumtopics (   id int,   name varchar(200) );
INSERT INTO forumtopics SET id = 1, name = "1st topic"; INSERT INTO
forumtopics SET id = 2, name = "2nd topic"; INSERT INTO forumtopics
SET id = 3, name = "3rd topic"; INSERT INTO forumtopics SET id = 4,
name = "4th topic"; INSERT INTO forumtopics SET id = 5, name = "5th
topic"; INSERT INTO forumtopics SET id = 6, name = "6th topic";

INSERT INTO forumposts SET id = 1, topicid=1, content = "1st post";
INSERT INTO forumposts SET id = 2, topicid=3, content = "2nd post";
INSERT INTO forumposts SET id = 3, topicid=3, content = "3rd post";
INSERT INTO forumposts SET id = 4, topicid=4, content = "4th post";
INSERT INTO forumposts SET id = 5, topicid=5, content = "5th post";
INSERT INTO forumposts SET id = 6, topicid=6, content = "6th post";
INSERT INTO forumposts SET id = 7, topicid=6, content = "7th post";

您可以在http://sqlfiddle.com上测试查询。