I built a custom forum for my site using MySQL. The listing page is essentially a table with the following columns: Topic, Last Updated, and # Replies.
The DB table has the following columns:
id
name
body
date
topic_id
email
A topic has the topic_id of “0”, and replies have the topic_id of their parent topic.
SELECT SQL_CALC_FOUND_ROWS
t.id, t.name, MAX(COALESCE(r.date, t.date)) AS date, COUNT(r.id) AS replies
FROM
wp_pod_tbl_forum t
LEFT OUTER JOIN
wp_pod_tbl_forum r ON (r.topic_id = t.id)
WHERE
t.topic_id = 0
GROUP BY
t.id
ORDER BY
date DESC LIMIT 0,20;
There are about 2,100 total items in this table, and queries usually take a whopping 6 seconds. I added an INDEX to the “topic_id” column, but that didn’t help much. Are there any ways of speeding up this query w/out doing significant restructuring?
EDIT: not quite working yet. I can’t seem to get the examples below to work properly.
If your table is
MyISAMoridis not aPRIMARY KEY, you need to create a composite ondex on(topic_id, id).If your table is
InnoDBandidis aPRIMARY KEY, an index just on(topic_id)will do (idwill be implicitly added to the index).Update
This query will most probably be even more efficient, provided that you have indexes on
(topic_id, id)and(date, id):See this article in my blog for performance details:
This query completes in
30 mson a100,000rows sample data:Both indexes are required for this query to be efficient.
If your table is
InnoDBandidis aPRIMARY KEY, then you can omit id from theindexesabove.