我有两个问题:
SELECT * FROM `kamcms_forum_post`
WHERE date=(SELECT max(date)
FROM `kamcms_forum_post`
WHERE `forum_topic_id` = [THERE IS PLACE FOR `forum_topic_id` from second query])
SELECT *, count(*) as posts
FROM `kamcms_forum_topic` as t
LEFT OUTER JOIN `kamcms_forum_post` as p ON t.forum_topic_id = p.forum_topic_id
GROUP BY t.forum_topic_id ORDER BY p.forum_post_id
第一个查询从主题获取最后一个帖子,第二个查询从主题和topic_name(从其他表)获取第一个帖子,并从主题获取所有帖子的计数。我如何加入这些查询?
输入:
kamcms_forum_topic
kamcms_forum_post
输出:
标题来自forum_topic, 首先在forum_post上发布user_id和last date以及user_id。
答案 0 :(得分:0)
第一个问题,您的第二个查询将始终至少返回1,以便对您的左连接主题进行计数。这应该与我对你的要求的理解非常接近。
SELECT t.title, p.user_id, p2.user_id, p2.date, count(p.forum_topic_id) as posts
FROM kamcms_forum_topic as t
LEFT OUTER JOIN kamcms_forum_post as p ON t.forum_topic_id = p.forum_topic_id
LEFT OUTER JOIN kamcms_forum_post as p2 ON t.forum_topic_id = p2.forum_topic_id
WHERE p.date=((SELECT MIN(date)
FROM kamcms_forum_post sp where sp.forum_post_id = p.forum_post_id)
AND p2.date=((SELECT MAX(date)
FROM kamcms_forum_post sp where sp.forum_post_id = p2.forum_post_id)
GROUP BY t.forum_topic_id ORDER BY p.forum_post_id
答案 1 :(得分:0)
最终查询:
SELECT t.title, p.user_id, p2.user_id, p2.date, count(p3.forum_post_id) as posts
FROM kamcms_forum_topic as t
LEFT OUTER JOIN kamcms_forum_post as p ON t.forum_topic_id = p.forum_topic_id
LEFT OUTER JOIN kamcms_forum_post as p2 ON t.forum_topic_id = p2.forum_topic_id
LEFT OUTER JOIN kamcms_forum_post as p3 ON t.forum_topic_id = p3.forum_topic_id
WHERE p.date=(SELECT MIN(date)
FROM kamcms_forum_post sp where sp.forum_topic_id = p.forum_topic_id)
AND p2.date=(SELECT MAX(date)
FROM kamcms_forum_post sp where sp.forum_topic_id = p2.forum_topic_id)
GROUP BY t.forum_topic_id ORDER BY p.forum_post_id
感谢您的帮助