gpt4 book ai didi

mysql - 如何处理多个连接

转载 作者:搜寻专家 更新时间:2023-10-30 23:40:15 26 4
gpt4 key购买 nike

我有一个复杂的查询,它需要总共 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 很简单,复制源代码并删除每个中的一个 ORed 条件:

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 是否有索引?

关于mysql - 如何处理多个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35793086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com