mysql - 如何摆脱内部连接中的 OR 条件

标签 mysql sql database performance

<分区>

我有一个复杂的查询,它需要总共 4 个表中的字段。我有一个包含 OR 子句的内部连接语句,这大大降低了查询速度。

这是我的查询:

   SELECT 
    pending_corrections.sightinguid AS 'pending_corrections_sightinguid',
    vehicle_ownership.id AS 'fk_vehicle_owner',
    @bill_id AS 'fk_bills',
    @nullValue AS 'fk_final_sightings_sightinguid',
    TRIM(pending_corrections.corrected_plate) AS 'vrn',
    pending_corrections.seenDate AS 'seen_date',
    cameras.in_out AS 'in_out',
    vehicle_vrn.fk_sysno AS 'fk_sysno',
    cameras.zone AS 'fk_zones',
    '0' AS 'auto_generated'
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.corrected_plate <> ''
        AND pending_corrections.corrected_plate IS NOT NULL
        AND pending_corrections.unable_to_correct <> '1'
        AND pending_corrections.seenDate >= @dateFrom
        AND pending_corrections.seenDate <= @dateTo
        AND (cameras.in_out = 1 OR cameras.in_out = 0)
        AND cameras.zone IN (SELECT 
            zone_number
        FROM
            zones
        WHERE
            fk_site = @siteId)
        AND seenDate >= vehicle_vrn.vrn_start_date
        AND (seenDate <= vehicle_vrn.vrn_end_date
        OR vehicle_vrn.vrn_end_date IS NULL
        OR vehicle_vrn.vrn_end_date = '0001-01-01 00:00:00')
        AND seenDate >= vehicle_ownership.ownership_start_date
        AND (seenDate <= vehicle_ownership.ownership_end_date
        OR vehicle_ownership.ownership_end_date IS NULL
        OR vehicle_ownership.ownership_end_date = '0001-01-01 00:00:00')
ORDER BY pending_corrections.corrected_plate , pending_corrections.seenDate ASC;

如何在其中一个连接中没有 OR 的情况下实现相同的效果? OR 子句的原因是因为 pending_corrections.corrected_plate 值必须匹配 vrn500vrnno 列在 vehicle_vrn 表中。

最佳答案

您可以使用 IN 表达式,而不是使用两个带有 OR 的等式表达式,例如:

FROM
    (pending_corrections
    INNER JOIN cameras ON pending_corrections.camerauid = cameras.camera_id)
        INNER JOIN 
    vehicle_vrn ON pending_corrections.corrected_plate IN(vehicle_vrn.vrn500, vehicle_vrn.vrnno)
        INNER JOIN
    vehicle_ownership ON vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno

关于mysql - 如何摆脱内部连接中的 OR 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35796832/

相关文章:

php - 'problem_id' 中的未知列 'field list'

javascript - 从 value 属性获取 <li> 元素的值

MySQL查询语法当数据从select更新查询时(多行)

php - 使用 PHP 和 MySQL 从多维关联数组插入到多个表中

php - 使用php解析sql文件

php - 从多维数组中的查询获取数据

python - 使用 utf8mb4 连接到 mysql 5.7.9 数据库时出现问题

php - 将删除按钮添加到显示 mysql 表内容的 php 代码中

database - SQL Server 2008 中从数据库到数据集的位数据类型到枚举类型的映射

mysql - 在 MySQL 过程中获取 SQLEXCEPTION 消息