mysql - 大咨询使用时速度慢 "ORDER BY"

标签 mysql sql

在论坛结构中排序一系列“主题”时遇到问题,当我执行查询时,会非常快(0.12秒)生成一个列表(在数百万条记录中),但是当我添加“ORDER BY”时ordered DESC”查询需要1分钟。

        SELECT 
        forum_topics.id AS id,
        forum_topics.slug AS slug, 
        forum_topics.user_id AS user_id, 
        forum_topics.forum_id AS forum_id, 
        forum_topics.title AS title,
        forum_topics.total_post AS total_post,  
        forum_topics.total_view AS total_view,
        forum_topics.last_post_id AS last_post_id,
        forum_topics.created AS created,
        forum_topics.modified AS modified,
        forum_topics.ordered AS ordered, 
        forum_topics.status_close AS status_close,
        forum_topics.status_view AS status_view, 
        t_users.id AS topic_user_id, 
        t_users.nick AS user_nick, 
        p_users.id AS post_user_id, 
        p_users.nick AS post_user_nick,
        forum_posts.title AS post_title, 
        forum_posts.created AS post_created 
        FROM forum_topics 
        LEFT JOIN forum_posts ON forum_topics.last_post_id = forum_posts.id 
        LEFT JOIN users AS t_users ON forum_topics.user_id = t_users.id 
        LEFT JOIN users AS p_users ON forum_posts.user_id = p_users.id 
        WHERE forum_topics.forum_id = '9' AND forum_topics.status_highlight = '0' 
        LIMIT 0,100

关于如何在不损失性能的情况下订购这个 super 表有什么想法吗? 注意:所有“id”(PRIMARY)和“*_id”都是索引,作为“ordered”字段,它是unix时间戳INT(15)

谢谢

最佳答案

使用 LIMIT 而不使用 ORDER BY 允许系统获取任意 100 条记录,因此它会获取找到的第一个记录。

添加 ORDER BY 表示您需要大约 100 条特定记录 - 因此它必须精确搜索这些记录。

如何解决?

尝试在FORUM_TOPICS(forum_id,status_highlight,ordered)上建立索引,该索引已经按照ORDER BY所需的顺序排列 - 因此,第一个(或最后一个) ) 索引中的记录就是您所请求的记录,因此数据库可以立即使用它们。

关于mysql - 大咨询使用时速度慢 "ORDER BY",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4700497/

相关文章:

java - SQL异常: inconsistent datatypes: expected TIMESTAMP got NUMBER

mysql - 如何搜索所有表记录,如果不存在则创建一个新的空记录?

mysql - MySQL 中何时使用单引号、双引号和反引号

PHP SQL find™ 和其他特殊字符

mysql - 如何获取多对多表中的相邻元素?

sql - Oracle - 整数数据类型精度最大值?我可以在整数字段中输入超过 38 个数字

sql - 包含 INSERT 语句的 WHERE 子句、WHERE 处的 "Incorrect Syntax"以及 IF NOT EXISTS 运行,无论记录是否存在

php - sql_查询 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

php - 如果不为空则回显相关表行 - PHP

mysql - 如何从MYSQL中选择准确的句子