我的网站突然开始出现以下错误:
"Incorrect key file for table '/tmp/#sql_645a_1.MYI'; try to repair it"
我删除它,该网站工作正常。
我的服务器技术支持人员建议我清理查询并使其更加高效。
这是查询:
SELECT *, FROM_UNIXTIME(post_time, '%Y-%c-%d %H:%i') as posttime
FROM communityposts, communitytopics, communityusers
WHERE communityposts.poster_id=communityusers.user_id
AND communityposts.topic_id=communitytopics.topic_id
ORDER BY post_time DESC LIMIT 5
非常感谢任何帮助。也许可以通过 JOIN 来完成?
非常感谢,
斯科特
更新:这是工作查询,但我仍然认为它可以优化。
SELECT
communityposts.post_id, communityposts.topic_id, communityposts.post_time,
communityusers.user_id, , communitytopics.topic_title, communityusers.username,
communityusers.user_avatar,
FROM_UNIXTIME(post_time, '%Y-%c-%d %H:%i') as post time
FROM
communityposts,
communitytopics,
communityusers
WHERE
communityposts.poster_id=communityusers.user_id
AND communityposts.topic_id=communitytopics.topic_id
ORDER BY post_time DESC LIMIT 5
最佳答案
SELECT
A.*,B.*,C.*,FROM_UNIXTIME(post_time, '%Y-%c-%d %H:%i') as posttime
FROM
(
SELECT id,poster_id,topic_id
FROM communityposts
ORDER BY post_time DESC
LIMIT 5
) cpk
INNER JOIN communityposts A USING (id)
INNER JOIN communityusers B ON cpk.poster_id=B.user_id
INNER JOIN communitytopics C USING (topic_id);
如果社区帖子不必具有用户和主题,则对最后两个连接使用 LEFT JOIN。
您需要为 cpk 子查询创建支持索引:
ALTER TABLE communityposts ADD INDEX (posttime,id,poster_id,topic_id);
此查询必须是最快的,因为 cpk 子查询始终只获取五个键。
更新2011-10-10 16:28 EDT
此查询消除了不明确的 topic_id 问题:
SELECT
A.post_id, cpk.topic_id, A.post_time,
B.user_id, C.topic_title, B.username,
B.user_avatar,
FROM_UNIXTIME(post_time, '%Y-%c-%d %H:%i') as posttime
FROM
(
SELECT id,poster_id,topic_id
FROM communityposts
ORDER BY post_time DESC
LIMIT 5
) cpk
INNER JOIN communityposts A USING (id)
INNER JOIN communityusers B ON cpk.poster_id=B.user_id
INNER JOIN communitytopics C ON cpk.topic_id=C.topic_id;
关于mysql - 编写 MySQL 查询的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7668250/