我一直在想弄清楚我做错了什么,让我解释一下我的MySQL结构(所以你得到了更好的理解),直到我直接回答这个问题。
我有一个简单的PHP论坛,如果它等于0表示显示(被视为未删除/存在)或者如果它等于1则隐藏了(如果它等于0)我在两个表(用于帖子和主题)中都有一个名为'deleted'的列被认为已删除/不存在) - bool / lean。
现在,我正在讨论'特定标准'...我想要使用其ID(forum_id)获取特定论坛中的总帖子数,确保它只计算未删除的帖子(删除) = 0)并且它们的父主题也不会被删除(删除= 0)。
列/表名称是不言自明的(如果需要,请参阅下面我的努力)。
我尝试了以下内容(使用'简单'加入):
SELECT COUNT(t1.post_id)
FROM forum_posts AS t1, forum_topics AS t2
WHERE t1.forum_id = '{$forum_id}'
AND t1.deleted = 0
AND t1.topic_id = t2.topic_id
AND t2.deleted = 0
LIMIT 1
我也试过这个(使用子查询):
SELECT COUNT(t1.post_id)
FROM forum_posts AS t1
WHERE t1.forum_id = '{$forum_id}'
AND t1.deleted = 0
AND (SELECT deleted
FROM forum_topics
WHERE topic_id = t1.topic_id) = 0
LIMIT 1
但两者都不符合具体标准。
感谢所有帮助! :)
答案 0 :(得分:1)
SELECT
COUNT(*) AS total
FROM
forum_topics
JOIN
forum_posts ON topic_id
WHERE
forum_topics.deleted = 0
AND forum_posts.deleted = 0
AND forum_posts.forum_id = '{$forum_id}'
这将使用topic_id连接两个表,并且仅返回符合已删除= 0和所需论坛ID的两个表的条件的结果。
答案 1 :(得分:0)
我不确定我理解您的问题,但您可以从以下查询开始并对其进行微调以执行您想要的操作:
SELECT COUNT(*)
FROM topic_posts AS TP
WHERE forum_id='{$forum_id}' AND
deleted=0 AND -- Count topic posts that are not deleted and...
NOT EXISTS ( -- make sure they are not for a deleted forum
SELECT * FROM forum_posts
WHERE forum_id=TP.forum_id and
deleted<>0)
我在查询中添加了评论以帮助您。