This query on my site is taking a very long time to execute. I have a blog and a forum on my site that I have loosely integrated so every forum account has an account on the blog and vice versa. However the user_id’s in each table aren’t correlated so I have been joining them by username.
SELECT *
FROM comments AS c
INNER JOIN articles AS a ON c.article_id = a.article_id
INNER JOIN user_profiles AS p ON c.user_id = p.user_id
INNER JOIN blog_users AS b ON c.user_id = b.user_id
INNER JOIN forum_users AS f ON b.username = f.username
WHERE a.article_id = :article_id
ORDER BY c.comment_id DESC
LIMIT 0 , 30
When I used explain on the query I saw that the last join was examining every single row in the forum_users table to come up with the result which is over 1,000,000 rows. The username columns for both tables are indexed and all tables are InnoDB. As a workaround, I’m storing each user’s forum user_id in the blog_users table, and vice versa so I can join directly on the user_id which has the query running much quicker but I would like to avoid having to do this if possible. Is there a way I could rework the query so the username join is more efficient?
Are the table and column character sets the same? For example, blog_users in utf8 and forum_users in latin1? If they aren’t the same, mysql won’t use the indexes. You can change the character set with, for example:
ALTER TABLE blog_users CONVERT TO CHARACTER SET utf8If this is the problem, read the docs carefully before doing this. It can change the content of the columns. http://dev.mysql.com/doc/refman/5.1/en/alter-table.html