你可以嘗試以下方法:
select
pending_corrections.corrected_plate , pending_corrections.seenDate
from pending_corrections
where pending_corrections.seenDate >= '2015-01-01 00:00:00'
and pending_corrections.seenDate <= '2015-01-31 23:59:59'
and exists(select 1 from cameras where pending_corrections.camerauid = cameras.camera_id)
and exists(select 1 from vehicle_ownership where vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno)
and exists(select 1 from vehicle_vrn
where pending_corrections.corrected_plate in (vehicle_vrn.vrnno, vehicle_vrn.vrn500))
order by 1,2;
或者稱爲已經提到dnoeth:
select * from (
select
pending_corrections.corrected_plate , pending_corrections.seenDate
from pending_corrections
where pending_corrections.seenDate >= '2015-01-01 00:00:00'
and pending_corrections.seenDate <= '2015-01-31 23:59:59'
and exists(select 1 from cameras where pending_corrections.camerauid = cameras.camera_id)
and exists(select 1 from vehicle_ownership where vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno)
and exists(select 1 from vehicle_vrn where pending_corrections.corrected_plate = vehicle_vrn.vrnno)
union
select
pending_corrections.corrected_plate , pending_corrections.seenDate
from pending_corrections
where pending_corrections.seenDate >= '2015-01-01 00:00:00'
and pending_corrections.seenDate <= '2015-01-31 23:59:59'
and exists(select 1 from cameras where pending_corrections.camerauid = cameras.camera_id)
and exists(select 1 from vehicle_ownership where vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno)
and exists(select 1 from vehicle_vrn where pending_corrections.corrected_plate = vehicle_vrn.vrn500)
) by 1,2;
PS當然,我無法測試它自己,而無需數據,知道所有的指標
這種連接狀態看起來並不好:(pending_corrections.corrected_plate = vehicle_vrn.vrn500 OR pending_corrections.corrected_plate = vehicle_vrn.vrnno) - 在性能方面.. 。您是否嘗試使用EXISTS(...)子查詢而不是INNER JOINS,因爲您沒有從連接表中選擇任何數據? – MaxU
'OR'ed連接條件是非常糟糕的(防止索引使用),常用的解決方法是使用'UNION'重寫。 – dnoeth
@dnoeth你會碰巧建議如何使用UNION來制定它嗎? –