MySQL 查询速度极慢

标签 mysql innodb optimization

你好我正在寻找优化 mysql 查询的方法,基本上我正在为属于 category_id = 25 和 source_id 的用户获取文章,而不是在我存储用户已取消订阅的源 ID 的表中。

select
  a.article_id,
  a.article_title,
  a.source_id,
  a.article_publish_date,
  a.article_details,
  n.source_name
from sources n
  INNER JOIN articles a
    ON (a.source_id = n.source_id)
WHERE n.category_id = 25
    AND n.source_id NOT IN(select
                 source_id
               from news_sources_deselected
               WHERE user_id = 5)
ORDER BY a.article_publish_date DESC

文章表的架构

CREATE TABLE IF NOT EXISTS `articles` (<br>
  `article_id` int(255) NOT NULL auto_increment,<br>
  `article_title` varchar(255) NOT NULL,<br>
  `source_id` int(255) NOT NULL,<br>
  `article_publish_date` bigint(255) NOT NULL,<br>
  `article_details` text NOT NULL,<br>
  PRIMARY KEY  (`article_id`),<br>
  KEY `source_id` (`source_id`),<br>
  KEY `article_publish_date` (`article_publish_date`)<br>
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='Contains articles.';

源表的结构

CREATE TABLE IF NOT EXISTS `sources` (<br>
  `source_id` int(255) NOT NULL auto_increment,<br>
  `category_id` int(255) NOT NULL,<br>
  `source_name` varchar(255) character set latin1 NOT NULL,<br>
  `user_id` int(255) NOT NULL,<br>
  PRIMARY KEY  (`source_id`),<br>
  KEY `category_id` (`category_id`),<br>
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='News Sources.'

articles 表有大约 30 万条记录,sources 表包含大约 1000 条记录,查询执行大约需要 180 秒。

任何帮助将不胜感激。

enter image description here

最佳答案

尝试使用带有 IS NULL 条件的派生查询。你解释说有一个依赖子查询。忽略使用它并使用派生查询来解决您的问题。这将提高性能

select
  a.article_id,
  a.article_title,
  a.source_id,
  a.article_publish_date,
  a.article_details,
  n.source_name
from sources n
  INNER JOIN articles a
    ON (a.source_id = n.source_id)
  LEFT JOIN (SELECT *
         FROM news_sources_deselected
         WHERE user_id = 5) AS nsd
    ON nsd.source_id = n.source_id
WHERE n.category_id = 25
    AND nsd.source_id IS NULL
ORDER BY a.article_publish_date DESC

关于MySQL 查询速度极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15921603/

相关文章:

c++ - 如何以最少的重复管理并行和顺序版本代码?

arrays - (Julia) 快速对数组进行按列求和

iphone - 优化 iPhone 性能

php - Laravel 计算列值为 1 的行

mysql - Magento 1.8 : Lock wait timeout issues when customer is checking out

mysql - Group BY 和 ORDER BY 优化

mysql - 如何处理 mysql innodb 表中 "select for update"作业的排队

mysql - 从 MyISAM 迁移到 InnoDB

mysql - 查询 MySQL 以获取给定英里半径内的纬度和经度坐标

php - 需要上传图片时出现的问题