【发布时间】:2015-04-30 06:45:53
【问题描述】:
我有两个表:Posts 和Tags,它们存储用户发布的文章以及他们附加到文章的标签。一个表PostTags用来表示文章ID和标签ID的关系。结构如下:
帖子:
id | title | author_id | create_time | update_time | ... #(title, author_id, create_time) is unique
标签:
id | tag_text | create_time #tag_text is unique and index
帖子标签:
id | post_id | tag_id #(post_id, tag_id) is unique
我现在使用下面的sql来获取带有相应标签的文章(使用group_concat)。
SELECT p.id, p.title, t.tag AS Tags FROM Posts p
LEFT JOIN Tags t on t.id IN
(SELECT tag_id FROM PostTags WHERE post_id=s.id)
GROUP BY p.id ORDER BY p.update_time DESC LIMIT 0, 10
但我发现它非常慢(对于 2.5k 行文章和 600 个标签,它需要 >3s)。如何提高性能?
EXPLAIN结果如下:
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | PRIMARY | p | ALL | NULL | NULL | NULL | NULL | 2569 | Using temporary; Using filesort
1 | PRIMARY | t | ALL | NULL | NULL | NULL | NULL | 616
2 | DEPENDENT SUBQUERY | PostTags | index_subquery | unique_index,tag_id,post_id |
tag_id | 4 | func | 1 | Using where
PS,我原来的sql是(with group_concat)
SELECT p.id, p.title, group_concat(DINSTINCT t.tag) AS Tags FROM Posts p
LEFT JOIN Tags t on t.id IN
(SELECT tag_id FROM PostTags WHERE post_id=s.id)
GROUP BY p.id ORDER BY p.update_time DESC LIMIT 0, 10
但是没有 group_concat 的情况是一样的。
【问题讨论】:
-
您在查询中使用 group_concat 的位置???
-
哎呀,本来我以为 group_concat 会有影响;但是在我发布这个问题的过程中,我尝试了没有 group_concat 的案例,但发现它仍然很慢。所以这个问题有些不一致。刚刚编辑。