mysql选择表1加入并按表2排序,优化filesort

时间:2012-11-02 05:57:51

标签: mysql temporary filesort

阅读mysql帖子但无法找到解决方案。

任何指针都会受到赞赏。

我有2张桌子A,B 表A将folderid映射到多个feedid(1到多个) 表B包含与其相关的feedid和数据。

以下查询给出了使用索引;使用临时;使用filesort

SELECT A.feed_id,B.feed_id,B.entry_id 
FROM feed_folder A 
LEFT JOIN feed_data B on A.feed_id=B.feed_id 
WHERE A.folder_id=29  
AND B.entry_id <= 123 
AND B.entry_created <= '2012-11-01 21:38:54' 
ORDER by B.entry_created desc limit 0,20;  

关于如何避免临时文件排序的任何想法。

以下是表格结构

CREATE TABLE `feed_folder` (
  `folder_id` bigint(20) unsigned NOT NULL,
  `feed_id` bigint(20) unsigned NOT NULL,
  UNIQUE KEY `folder_id` (`folder_id`,`feed_id`),
  KEY `feed_id` (`feed_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `feed_data` (
  `entry_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `feed_id` bigint(20) unsigned NOT NULL,
  `entry_created` datetime NOT NULL,
  `entry_object` text,
  `entry_permalink` varchar(150) NOT NULL,
  `entry_orig_created` datetime NOT NULL,
  PRIMARY KEY (`entry_id`),
  UNIQUE KEY `feed_id_2` (`feed_id`,`entry_permalink`),
  KEY `entry_created` (`entry_created`),
  KEY `feed_id` (`feed_id`,`entry_created`),
  KEY `feed_id_entry_id` (`feed_id`,`entry_id`),
  KEY `entry_permalink` (`entry_permalink`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8

1 个答案:

答案 0 :(得分:0)

尝试此查询:

SELECT * FROM(SELECT
A.feed_id,B.feed_id,B.entry_id 
FROM feed_folder as A 
INNER JOIN feed_data as B on A.feed_id=B.feed_id 
WHERE A.folder_id=29  
AND B.entry_id <= 123 
AND B.entry_created <= '2012-11-01 21:38:54')joinAndSortTable
ORDER by B.entry_created desc limit 0,20;

问题在别名中,您忘记提供as Aas B 我也提醒你LEFT JOIN和RIGHT JOIN,INNER JOIN ...... 要加入您选择的所有记录,使用INNER JOIN是一种解决方法。 因为INNER JOIN可以使用完全访问权限加入所有列。

好运