什么是投票表的最佳索引?

时间:2017-06-06 06:00:21

标签: mysql sql indexing

这是我的问题:

SELECT qa.id,
       qa.subject,
       qa.category cat,
       qa.keywords tags,
       qa.body_html,
       qa.amount,
       qa.visibility,
       qa.date_time,
       COALESCE(u.reputation, 'N') reputation,
       COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'unknown') name,
       COALESCE(u.avatar, 'anonymous.png') avatar,

  (SELECT COALESCE(sum(vv.value),0)
   FROM votes vv
   WHERE qa.id = vv.post_id
     AND 15 = vv.table_code) AS total_votes,

  (SELECT COALESCE(sum(vt.total_viewed),0)
   FROM viewed_total vt
   WHERE qa.id = vt.post_id
     AND 15 = vt.table_code
   LIMIT 1) AS total_viewed
FROM qanda qa
LEFT JOIN users u ON qa.author_id = u.id
AND qa.visibility = 1
WHERE qa.type = 0
ORDER BY qa.date_time DESC
LIMIT 0,
      11;

以下是EXPLAIN的结果:

enter image description here

请参阅?最后一行(vv)对任何索引都没有好处。此处还有votes表上的当前索引:

enter image description here

无论如何,你的建议是什么?我需要什么指数才能使性能更好?

1 个答案:

答案 0 :(得分:0)

我认为您需要将qa.visibility = 1LEFT JOIN..ON移至WHERE。完成后,请使用以下索引:

qanda:  INDEX(visibility, type, date_time)  -- date_time must be last

这将完全处理WHEREORDER BYLIMIT - 这可能是性能的最大提升。

vv and vt:  INDEX(post_id, table_code) -- in either order

您似乎有(post_id, table_code, user_id)。如果这是唯一的,那么将其宣传为PRIMARY KEY并摆脱id;这会给你一点额外的提升。

我认为usersPRIMARY KEY(id)

LIMIT 1子查询中不需要vt

如果您需要进一步讨论,请为每个表格提供SHOW CREATE TABLE