0

我正在使用以下 SQL 查询,但执行时间超过 180 秒。有没有办法加快速度?这个 SQL 给了我所有女性的 pic_id 和。

SELECT pic_id, small
FROM picture
WHERE hide =0
AND userhide =0
AND  `fbid` 
IN (

      SELECT fbid
      FROM user
      WHERE gender =  "female"
   )

ORDER BY  `picture`.`pic_id` ASC 
LIMIT 1500 , 200

解释 SQL

id select_type         table    type   possible_keys  key      key_len  ref   rows  Extra
1  PRIMARY             picture  index  NULL           PRIMARY  4        NULL  1700  Using where
2  DEPENDENT SUBQUERY  user     ALL    NULL           NULL     NULL     NULL  7496  Using where

--- Tim 的 sql 答案的解释语句结果 --

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  picture ALL NULL    NULL    NULL    NULL    41443   Using where; Using temporary; Using filesort
1   SIMPLE  user    ALL NULL    NULL    NULL    NULL    7501    Using where; Using join buffer

- 结构 - -

CREATE TABLE `user` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 NOT NULL,
`first_name` varchar(255) CHARACTER SET utf8 NOT NULL,
`username` varchar(255) CHARACTER SET utf8 NOT NULL,
`birthday` date NOT NULL,
`location` varchar(255) CHARACTER SET utf8 NOT NULL,
`gender` varchar(6) CHARACTER SET utf8 NOT NULL,
`created` date NOT NULL,
`fbid` bigint(50) NOT NULL,
`token` varchar(255) CHARACTER SET utf8 NOT NULL,
`relationship_status` varchar(20) CHARACTER SET utf8 NOT NULL,
`smallest` varchar(255) CHARACTER SET utf8 NOT NULL,
`email` varchar(40) CHARACTER SET utf8 NOT NULL,
`ref` varchar(15) NOT NULL,
PRIMARY KEY (`sid`),
KEY `gender` (`gender`),
KEY `fbid` (`fbid`)
) ENGINE=MyISAM AUTO_INCREMENT=7595 DEFAULT CHARSET=latin

---- 图片表的结构 ---

CREATE TABLE `picture` (
 `fbid` bigint(50) NOT NULL,
 `pic_id` int(11) NOT NULL AUTO_INCREMENT,
 `pic_location` varchar(255) NOT NULL,
 `hide` int(1) NOT NULL,
 `small` varchar(255) NOT NULL,
 `userhide` int(1) NOT NULL,
 `likes` int(10) NOT NULL,
 `hot` int(1) NOT NULL,
 PRIMARY KEY (`pic_id`),
 UNIQUE KEY `pic_location` (`pic_location`),
 UNIQUE KEY `small` (`small`),
 KEY `fbid` (`fbid`),
 KEY `hide` (`hide`),
 KEY `userhide` (`userhide`)
) ENGINE=MyISAM AUTO_INCREMENT=42749 DEFAULT CHARSET=latin1
4

2 回答 2

4

尝试这样的事情:

SELECT pic_id, small
FROM picture
INNER JOIN user ON ( picture.fbid = user.fbid and user.gender='female' )
WHERE hide =0
AND userhide =0
ORDER BY  `picture`.`pic_id` ASC 
LIMIT 1500 , 200

我将性别放入连接中,因为查询不会返回在内连接上不匹配的行。

您还应该阅读此堆栈溢出主题

编辑:

确保您已索引以下字段:

picture.fbid
user.fbid
user.gender
picture.hide
picture.userhide
于 2012-09-20T04:59:24.070 回答
1

尝试使用连接:

SELECT p.pic_id, p.small
FROM picture p
INNER JOIN fbid f USING ( fbid )
WHERE p.hide =0
AND p.userhide =0
AND f.gender = 'female'
ORDER BY  `picture`.`pic_id` ASC 
LIMIT 1500 , 200
于 2012-09-20T04:58:54.347 回答