我有相当大的查询,这基本上显示了不同的论坛我已经保存在我的数据库,我的用户:PHP - 加入语句复制记录
$stmt = $dbh->prepare("
SELECT
c.forum_id as category_id,
c.forum_name as category_name,
t.forum_id as id,
t.forum_name as name,
t.forum_desc as description,
(SELECT COUNT(*) FROM forum_topics WHERE forum_id=t.forum_id AND topic_deleted=0) as topics_count,
(SELECT COUNT(*) FROM forum_posts WHERE forum_id=t.forum_id AND post_deleted=0) as posts_count,
(SELECT COUNT(*) FROM forum_posts WHERE topic_id=lp.topic_id AND post_deleted=0) as last_post_count,
lp.topic_id as last_post_topic_id,
lp.topic_title as last_post_topic_title,
lp.post_time as last_post_time,
lp.username as last_post_username
FROM forum_cats as t
JOIN forum_cats as c on c.forum_id = t.forum_type_id
left join (
SELECT
ft.topic_id,
ft.title as topic_title,
tmp.post_time,
u.username,
fp.forum_id
FROM
forum_posts fp
join forum_topics ft on ft.topic_id = fp.topic_id
join users u on u.id = fp.userid
join (
select forum_id, max(`post_time`) `post_time`
from forum_posts fp
where fp.post_deleted = 0
group by forum_id
) as tmp on (fp.forum_id = tmp.forum_id and fp.post_time = tmp.post_time)
where post_deleted = 0 and ft.topic_deleted = 0
) as lp on lp.forum_id = t.forum_id
where t.forum_active = 1 and c.forum_active = 1
order by category_id, t.forum_id
");
$stmt->execute();
我然后做一个while循环来显示所有的记录:
while (($row = $stmt->fetch())) {
echo $row['name'];
}
的问题是,while循环过程中,我获得优秀成果有时!
它应该是这样的:
forum1
forum2
forum3
forum4
forum5
forum6
等
但有时我得到的结果是这样的:
forum1
forum1
forum1
forum1
forum2
forum3
forum4
forum5
forum6
某些行(这是相当随机哪一行)是被“重复”。
有人能帮我解释一下吗?
据推测,查询'选择t.forum_id FROM t'生成相同的错误forum_topics? – Strawberry 2014-09-21 08:16:39
@Strawberry你愿意详细说明吗? – oliverbj 2014-09-21 08:21:13
只是一个疯狂的猜测,但...我会说你的第三次加入(子查询)是带来的主要查询职位使重复,因为您可能有一个论坛的许多职位。你可以单独运行子查询(你把它命名为'lp''')并检查是否有重复的'''forum_id'''字段? – mTorres 2014-09-21 08:23:12