【发布时间】:2012-05-19 08:21:09
【问题描述】:
我有三个表:categories、articles和article_events,结构如下
categories: id, name (100,000 rows)
articles: id, category_id (6000 rows)
article_events: id, article_id, status_id (20,000 rows)
每个文章行的最高 article_events.id 描述了每篇文章的当前状态。
我正在返回一个类别表以及其中有多少篇最新事件 status_id 为“1”的文章。
到目前为止,我所做的工作,但对于我的表格大小来说相当慢(10 秒)。想知道有没有办法让这个更快。据我所知,所有表都有适当的索引。
SELECT c.id,
c.name,
SUM(CASE WHEN e.status_id = 1 THEN 1 ELSE 0 END) article_count
FROM categories c
LEFT JOIN articles a ON a.category_id = c.id
LEFT JOIN (
SELECT article_id, MAX(id) event_id
FROM article_events
GROUP BY article_id
) most_recent ON most_recent.article_id = a.id
LEFT JOIN article_events e ON most_recent.event_id = e.id
GROUP BY c.id
基本上我必须加入 events 表两次,因为请求 status_id 和 MAX(id) 只会返回它找到的第一个 status_id,而不是与 MAX(id) 行关联的那个。
有什么方法可以让这变得更好吗?还是我只需要忍受 10 秒?谢谢!
编辑:
这是我对查询的解释:
ID | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
---------------------------------------------------------------------------------------------------------------------------
1 | PRIMARY | c | index | NULL | PRIMARY | 4 | NULL | 124044 | Using index; Using temporary; Using filesort
1 | PRIMARY | a | ref | category_id | category_id | 4 | c.id | 3 |
1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 6351 |
1 | PRIMARY | e | eq_ref | PRIMARY | PRIMARY | 4 | most_recent.event_id | 1 |
2 | DERIVED | article_events | ALL | NULL | NULL | NULL | NULL | 19743 | Using temporary; Using filesort
【问题讨论】:
-
请在此处发布
EXPLAIN ...的输出以供您查询。
标签: mysql optimization group-by left-join