mysql - 编写 MySQL 查询的更有效方法?

标签 mysql optimization

我的网站突然开始出现以下错误:

"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/

相关文章:

mysql - 删除MySQL中包含[A-Za-z0-9]以外的所有字符的行

php - 删除基于php中varchar主键的行

c++ - std::string 和多重连接

c++ - 如果我的进程在事件之间处于空闲状态,为什么延迟会更大?

MySQL 错误代码 : 1452 when adding index and foreign key constraints to an existing table

mysql - 为什么导入的数据库在 phpmyadmin 中较小?

mysql - html5与mysql直连

c - 根据另一个数组中设置的值打印一个数组的元素

python - 如何加速 Cython 代码来计算 dirichlet 的条件对数似然?

.net - .NET中的内存泄漏