检查另一个表的数据的SQL查询

时间:2011-11-13 12:32:20

标签: php sql forum

对于像JOIN这样更复杂的SQL查询,我不太好,所以我在这方面一点都不了。

我有三张桌子:

FORUM_Topics
FORUM_Threads
FORUM_Replies

论坛主题是最高级别。

论坛帖子在主题内。

论坛回复在线程内。

回复并没有直接说出他们所处的主题,只说明了什么主题。然后线程说出了什么主题。

所以它看起来像这样:

FORUM_Topics
ID = 1
Name = A topic

FORUM_Threads
ID = 1
TopicID = 1
Name = A forum thread

FORUM_Replies
ID = 1
ThreadID = 1
Name = A forum reply

如果我想查看主题中有多少个主题,那就简单如下:

$threads = mysql_query("SELECT * FROM FORUM_Threads WHERE TopicID = $ID");

但我如何查看某个主题中的回复数量?

3 个答案:

答案 0 :(得分:3)

select FORUM_Replies.* from FORUM_Replies
inner join FORUM_Threads on FORUM_Replies.ThreadID = FORUM_Threads.ID
where FORUM_Threads.TopicID = $ID

您可能希望从回复和主题获得结果。

select FORUM_Replies.Name as ReplyName, FORUM_Threads.Name as ForumName from FORUM_Replies
inner join FORUM_Threads on FORUM_Replies.ThreadID = FORUM_Threads.ID
where FORUM_Threads.TopicID = $ID

答案 1 :(得分:0)

我认为你应该使用这个查询

SELECT COUNT(*) FROM FORUM_Replies WHERE ThreadID IN (SELECT DISTINCT ID FROM FORUM_Threads WHERE TopicID = @id)

应该做的伎俩

答案 2 :(得分:0)

我猜是这样的:

SELECT
  COUNT(`forum_replies`.`name`) as `totals`
FROM
  `FORUM_REPLIES`
LEFT JOIN
  `forum_replies` ON(`forum_threads`.`topicid`=`forum_replies`.`threadid`)
LEFT JOIN
  `FORUM_THREDS` ON(`forum_topic`.`id`=`forum_threads`.`topicid`)
WHERE
  `forum_topics`.`id`="7";