4
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 秒,我想知道是否有人对我如何改进/优化它以实现更快的执行时间有任何建议?

4

3 回答 3

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;
于 2013-09-15T20:37:48.177 回答
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) )

这是我在没有看到表格的情况下从您的代码逆向工程的逻辑。

于 2013-09-15T20:37:53.057 回答
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
于 2013-09-15T20:59:49.633 回答