【发布时间】:2016-01-22 07:34:50
【问题描述】:
我有以下查询,我相信我已尽可能优化:
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,
lp.avatar
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,
u.avatar,
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
这是每个论坛的统计数据:
forum_cats has 20 rows
forum_topics has 900 rows
forum_posts has 9000 rows
users has 18000 rows
我已在上述查询中选择的所有列上添加了index。然而,执行此操作仍然需要 2 秒以上。
我在这里错过了什么?
【问题讨论】:
-
删除这两个子连接并将它们变成一个临时表。这应该会加快你的速度。
-
嘿!你介意举个例子吗?谢谢!
-
这种没有EXPLAIN输出的问题是没有意义的
-
@oliverbj 更新您的问题,以便清楚地理解问题,用示例数据显示您的 4 个表格并显示其中的预期数据,然后我们可以为您提供帮助。