关于如何优化MySQL查询以更快运行的建议

时间:2013-09-15 20:19:21

标签: mysql optimization

SELECT * 
FROM   members 
WHERE  memberid IN (SELECT follows.followingid 
                    FROM   follows 
                    WHERE  follows.memberid = '$memberid' 
                           AND follows.followingid NOT IN (SELECT memberid 
                                                           FROM   userblock)) 
       AND memberid NOT IN (SELECT blockmemberid 
                            FROM   userblock 
                            WHERE  memberid = '$memberid')

上面的查询在MySQL中执行需要将近4秒钟,我想知道是否有人对如何改进/优化它以实现更快的执行时间有任何建议?

3 个答案:

答案 0 :(得分:0)

in子句替换为连接。我认为以下内容捕获了逻辑。请注意,not in变为left joinwhere子句中的条件发现不匹配

SELECT m.* 
FROM members m
     follow f
     on m.memberid = f.followingid and 
        f.memberid = $memberid left join
     userblock ubf
     on follows.followingid = ubf.memberid left join
     userblock ub
     on m.memberid = ub.blockmemberid and
        ub.memberid = '$memberid'
where ub.blockmemberid is null and
      ubf.memberid is null;

答案 1 :(得分:0)

这看起来很相似,但你的嵌套查询较少。

SELECT * 
FROM   members m
WHERE  EXIST (SELECT f.followingid 
              FROM   follows f
              WHERE  f.memberid = '$memberid'
                     AND f.followingid = m.memberid)

       AND NOT EXIST (SELECT u.blockmemberid 
                      FROM   userblock u
                      WHERE  (m.memberid = '$memberid'
                             AND u.blockmemberid = m.memberid)
                          OR 
                             (u.blockmemberid = m.memberid
                             AND u.memberid = m.memberid) )

这是我从代码中反向设计的逻辑而没有看到表格。

答案 2 :(得分:0)

SELECT m.* 
FROM   members m
INNER JOIN follows f ON f.followingid = m.memberid AND
                        f.memberid = '$memberid'
LEFT OUTER JOIN userblock ub1 ON f.followingid = ub1.memberid 
LEFT OUTER JOIN userblock ub2 ON m.memberid = ub2.blockmemberid AND
                            ub2.memberid = '$memberid'
WHERE ub1.memberid IS NULL AND ub2.blockmemberid IS NULL