数据库
首页 > 数据库> > mysql-如何处理多个联接

mysql-如何处理多个联接

作者:互联网

我有一个复杂的查询,该查询总共需要4个表中的字段.内部联接导致查询花费的时间比应该花费的时间长得多.我运行了一个EXPLAIN语句,其视觉结果如下所示:

EXPLAIN Statement output

这是我的查询:

SELECT 
   pending_corrections.corrected_plate , pending_corrections.seenDate
FROM
    (pending_corrections
    INNER JOIN cameras ON pending_corrections.camerauid = cameras.camera_id)
        INNER JOIN
    vehicle_vrn ON (pending_corrections.corrected_plate = vehicle_vrn.vrn500
        OR pending_corrections.corrected_plate = vehicle_vrn.vrnno)
        INNER JOIN
    vehicle_ownership ON vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno
WHERE
    pending_corrections.seenDate >= '2015-01-01 00:00:00'
        AND pending_corrections.seenDate <= '2015-01-31 23:59:59'
ORDER BY pending_corrections.corrected_plate , pending_corrections.seenDate ASC;

如何实现相同的效果,但是其中一个联接中没有OR?

解决方法:

作为UNION重写很简单,复制源并删除每个条件中的OR条件:

SELECT 
   pending_corrections.corrected_plate , pending_corrections.seenDate
FROM
    (pending_corrections
    INNER JOIN cameras ON pending_corrections.camerauid = cameras.camera_id)
        INNER JOIN
    vehicle_vrn ON (pending_corrections.corrected_plate = vehicle_vrn.vrn500)
        INNER JOIN
    vehicle_ownership ON vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno
WHERE
    pending_corrections.seenDate >= '2015-01-01 00:00:00'
        AND pending_corrections.seenDate <= '2015-01-31 23:59:59'

union 

SELECT 
   pending_corrections.corrected_plate , pending_corrections.seenDate
FROM
    (pending_corrections
    INNER JOIN cameras ON pending_corrections.camerauid = cameras.camera_id)
        INNER JOIN
    vehicle_vrn ON pending_corrections.corrected_plate = vehicle_vrn.vrnno)
        INNER JOIN
    vehicle_ownership ON vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno
WHERE
    pending_corrections.seenDate >= '2015-01-01 00:00:00'
        AND pending_corrections.seenDate <= '2015-01-31 23:59:59'

ORDER BY 1,2;

是否有关于pending_corrections.seenDate的索引?

标签:performance,sql,mysql,database,relational-database
来源: https://codeday.me/bug/20191012/1901326.html