我正在开发一个PHP论坛。 本论坛使用四个数据库表:论坛,帖子,帖子,用户。孙子表的MySQL计数返回不同的结果
在我的着陆页上,我列出了所有论坛,以及最新线程列表(通过连接和内部连接实现),总体THAS(简单计数子查询)和总帖子。
我有一个合理大小的查询,返回以上所有内容,并且一切工作都很好 - 除了总帖子。
主查询是这样的:
select f.id as forum_id,
f.name as forum_name,
f.description,
t.forum_id,
#this subquery counts total threads in each forum
(select count(t.forum_id)
from thread t
where t.forum_id = f.id
) as total_threads,
#this query counts total posts for each forum
(SELECT COUNT(p.id)
FROM post p
WHERE p.thread_id = t.id
AND t.forum_id = f.id
GROUP BY f.id) as total_posts,
t.id as thread_id,
t.name as thread_name,
t.forum_id as parent_forum,
t.user_id,
t.date_created,
u.id as user_id,
u.username
from forum f
# this join finds all latest threads of each forum
join
(select forum_id, max(date_created) as latest
from thread
group by forum_id) as d on d.forum_id = f.id
#and this inner join grabs the rest of the thread table for each latest thread
inner join thread as t
on d.forum_id = t.forum_id
and d.latest = t.date_created
join user as u on t.user_id = u.id
所以,如果你将你的注意力总员额子查询以上 你会发现htat我指望所有职位,他们的线程ID =的ID每个线程然后=每个论坛的ID,如果我单独使用这个查询(并包括主查询中其他地方使用的表别名)它完美的作品。但是,当用于主查询的争用中,并且在别处提供表别名时,它只返回第一个线程p/forum的计数。
如果我尝试在子查询中声明表别名,它将返回多于一行已被返回的错误。
为什么关于查询内容的差异以及为什么只有第一个线程在主查询中用作计算字段时才被计算?