用JOIN语句替换“IN”

时间:2012-02-28 09:53:02

标签: mysql sql ms-access

访问迁移到 MySQL 时,我遇到了麻烦。

以下SQL语句适用于访问

SELECT *
FROM tbl_content 
WHERE contentID IN (
     SELECT contentID
     FROM tbl_tags
     WHERE Bezeichnung IN (
              SELECT Bezeichnung
              FROM tbl_tags t2
              WHERE t2.contentID= " & contentID & ")
     AND contentID <> " & contentID & ")
AND Status = 1
ORDER BY Datum DESC LIMIT 0,5;

MySQL 中,性能非常慢。有任何帮助的想法吗?

2 个答案:

答案 0 :(得分:2)

MySQL有一个已知的子查询问题,它会根据外部查询每次比较它们来评估它们。避免他们!这可能是您看到Access出现这种恶化的原因。

答案 1 :(得分:1)

您已在标题中回答了自己的问题。一般来说,MySQL不会优化IN (Subquery)以及JOINS,因此您最好使用JOIN

SELECT  *
FROM    tbl_content t1
        INNER JOIN
        (   SELECT  ContentID
            FROM    tbl_tags t1
                    INNER JOIN
                    (   SELECT  Bezeichnung 
                        FROM    tbl_tags t2 
                        WHERE   t2.contentID = " & contentID & "
                        GROUP BY Bezeichnung
                    ) t2
                        ON t1.Bezeichnung = t2.Bezeichnung
            WHERE   contentID <> " & contentID & "
            GROUP BY ContentID
        ) t2
            ON t2.ContentID = t1.ContentID
WHERE   Status = 1
ORDER BY Datum DESC LIMIT 0,5;

同时检查相关列是否已编入索引以提高性能。

修改

更多我认为EXISTS在MySQL中可能更有效率,但EXPLAIN应该显示更多:

SELECT  *
FROM    tbl_content t1
WHERE   EXISTS
        (   SELECT  1
            FROM    tbl_tags t2
            WHERE   EXISTS
                    (   SELECT  1
                        FROM    tbl_tags t3
                        WHERE   t2.contentID = " & contentID & "
                        AND     t2.Bezeichnung = t2.Bezeichnung
                    ) 
            AND     t1.ContentID = t2.ContentID
        ) 
AND     Status = 1
AND     t1.contentID <> " & contentID & "
ORDER BY Datum DESC LIMIT 0,5;