使用JOIN MySQL

时间:2016-07-27 09:59:56

标签: mysql performance join nested

为了提高性能,使用JOIN for MySQL 5.6+重写此查询是否有意义?如果是这样,怎么样?

SELECT col1, col2, col3 FROM tab WHERE 
col2 > 1234 
AND col2 < 9876 
AND col3 IN (1,2,3,4) 
AND col1 IN (SELECT col1 FROM tab 
             WHERE col3 IN (1,2,3,4) 
                 AND col4 = 10 
             GROUP BY col1 
             HAVING COUNT(DISTINCT col3) = 4)

1 个答案:

答案 0 :(得分:0)

我能想到的两种可能的解决方案。

首先,您要加入子查询,而不是使用IN子句

SELECT tab.col1, 
        tab.col2, 
        tab.col3 
FROM tab 
INNER JOIN
(
    SELECT col1 
    FROM tab 
    WHERE col3 IN (1,2,3,4) 
    AND col4 = 10 
    GROUP BY col1 
    HAVING COUNT(DISTINCT col3) = 4
) sub0
ON tab.col1 = sub0.col1
WHERE col2 > 1234 
AND col2 < 9876 
AND col3 IN (1,2,3,4) 
AND col1 IN 

根据比赛的数量等,这可能会更有效。

可能更高效,但不太灵活的是,对于col3的每个特定值,使用col4为10,您需要连接回表。如果缺少任何,则连接将导致排除该行。缺点是你需要在SELECT上使用DISTINCT来删除重复项。

SELECT DISTINCT tab0.col1, 
        tab0.col2, 
        tab0.col3 
FROM tab AS tab0
INNER JOIN tab AS tab1 ON tab0.col1 = tab1.col1 AND tab1.col3 = 1 AND tab1.col4 = 10
INNER JOIN tab AS tab2 ON tab0.col1 = tab2.col1 AND tab2.col3 = 2 AND tab2.col4 = 10
INNER JOIN tab AS tab3 ON tab0.col1 = tab3.col1 AND tab3.col3 = 3 AND tab3.col4 = 10
INNER JOIN tab AS tab4 ON tab0.col1 = tab4.col1 AND tab4.col3 = 4 AND tab4.col4 = 10
WHERE tab0.col2 > 1234 
AND tab0.col2 < 9876 
AND tab0.col3 IN (1,2,3,4)