堆叠多个日期和搜索字符串查询SQL

时间:2019-02-19 15:56:44

标签: mysql sql

我正在寻找清理代码的方法。下面的代码按预期工作,但我无法弄清楚如何将日期查询与使用'IN'查询的事故类型类似。似乎有太多代码可以在一组不同的日期执行相同的操作。我知道这与括号和使用逗号有关,但是我尝试并尝试过没有运气。 这是我的工作代码:

SELECT * FROM sa_incidents 
WHERE
    (incidentDate BETWEEN '2019-01-01' AND '2019-12-31' )
    AND
    incidentType 
    IN (
        'RIDDOR - Dangerous Occurrence',
        'RIDDOR - Public',
        'Non RIDDOR - Near Miss',
        'Non RIDDOR - Minor Injury'
    )
    OR (incidentDate  BETWEEN '2017-01-01' AND '2017-12-31')
    AND
    incidentType 
    IN (
        'RIDDOR - Dangerous Occurrence',
        'RIDDOR - Public',
        'Non RIDDOR - Near Miss',
        'Non RIDDOR - Minor Injury'
    )
    OR 
    (incidentDate BETWEEN '2016-01-01' AND '2016-12-31' )
    AND
    incidentType 
    IN (
        'RIDDOR - Dangerous Occurrence',
        'RIDDOR - Public',
        'Non RIDDOR - Near Miss',
        'Non RIDDOR - Minor Injury'
    )

1 个答案:

答案 0 :(得分:2)

如果您只是想减少不必要的编码,那就可以了

SELECT * FROM sa_incidents 
WHERE (
            incidentDate BETWEEN '2019-01-01' AND '2019-12-31'
        OR  incidentDate  BETWEEN '2017-01-01' AND '2017-12-31'
        OR  incidentDate BETWEEN '2016-01-01' AND '2016-12-31'
        )
AND incidentType IN (
                        'RIDDOR - Dangerous Occurrence',
                        'RIDDOR - Public',
                        'Non RIDDOR - Near Miss',
                        'Non RIDDOR - Minor Injury'
                    )
ORDER BY <something like the data probably>