优化困难的mySQL查询

时间:2014-04-18 20:20:41

标签: mysql sql

我正在开发论坛。表结构是:

forum_threads:
  id: int unsigned, primary key
  forum_id: int unsigned
  flags: int unsigned. (1 - closed, 2 - important, etc.)
  views: int unsigned

forum_thread_views_count: (is a MEMORY table, needed to reduce IO operations)
  thread_id: int unsigned, primary key
  views: int unsigned

forum_posts:
  id: int unsigned, primary key
  thread_id: int unsigned
  author_id: int unsigned
  flags: int unsigned
  creation_date: int unsigned (unix timestamp)

我需要选择:forum_thread.idforum_thread.flagsforum_thread.viewsforum_thread_views_count.viewsCOUNT(forum_posts)MIN(forum_posts.id)MAX(forum_posts.id)forum_thread.forum_id订购的forum_posts.creation_date DESC。首先必须选择重要的主题(旗帜和2)。

现在我有查询:

SELECT t.id, t.flags, t.views, tv.views, COUNT(p.id), MIN(p.id), MAX(p.id)
FROM forum_threads t
LEFT JOIN forum_thread_views_count tv ON tv.thread_id = t.id
LEFT JOIN forum_posts p ON p.thread_id = t.id
WHERE t.forum_id = 1
GROUP BY t.id
ORDER BY t.flags & 2 DESC, p.creation_date DESC;

这是有效的,但我认为它可以做得更好。

1 个答案:

答案 0 :(得分:1)

有两种方法可以让它变得更好。首先,除非有正确使用外连接的原因,否则请使用内连接。接下来,从

更改您的论坛
GROUP BY t.id

GROUP BY t.id, t.flags, t.views, tv,views

虽然MySQL允许您使select和group by子句不匹配,但可能会导致您获得不正确的结果。