這裏是我的查詢:什麼是投票表的最佳索引?
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
結果:
看到了嗎?最後一行(vv
)不會使任何索引受益。而且,這裏是在votes
表中的當前索引:
總之,什麼是你的建議嗎?我需要什麼指數才能使表現更好?
表的表決是否包含大量的數據或大量的共貨幣?你爲什麼不在柱子post_id的VOTE上添加PK,那麼你在post_id上有唯一的數據和索引,你可以在post_id和table_code上添加索引,因爲你在where條件中選擇ti – Moudiz
另外,LIMIT 1似乎是多餘 – Strawberry