SQL返回错误结果

时间:2019-04-05 12:46:58

标签: sql

我似乎错过了操作员优先级。这是我的要求:

SELECT
        "id",
        "arch_date2",
        "ftp_file_full_path",
        "isProcessing",
        "processing_status",
        "region",
        "isUnpacked",
        "section_name"
    FROM "ftp_files" WHERE "isUnpacked" IS NULL 
        AND "section_name" IN ('protocols','notifications','contracts')  
        AND ("region" = 'Chechenskaja_Resp' AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01')  
        OR ("region" = 'Arkhangelskaja_obl' AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01')  
        OR ("region" = 'Astrakhanskaja_obl' AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01')  
        OR ("region" = 'Bajkonur_g' AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01')  
        order by "region" LIMIT 1; 

但是结果是我与isUnpacked='True'发生冲突

enter image description here

1 个答案:

答案 0 :(得分:4)

WHERE子句中,您需要在整个区域部分加上括号:

FROM "ftp_files" WHERE "isUnpacked" IS NULL 
    AND "section_name" IN ('protocols','notifications','contracts')  
    AND (("region" = 'Chechenskaja_Resp' AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01')  
      OR ("region" = 'Arkhangelskaja_obl' AND arch_date2>='2018-01-01' AND arc h_date2<='2019-01-01')  
      OR ("region" = 'Astrakhanskaja_obl' AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01')  
      OR ("region" = 'Bajkonur_g' AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01'))
    order by "region" LIMIT 1; 

或简化为:

FROM "ftp_files" WHERE "isUnpacked" IS NULL 
    AND "section_name" IN ('protocols','notifications','contracts')  
    AND "region" IN ('Chechenskaja_Resp', 'Arkhangelskaja_obl',
                     'Astrakhanskaja_obl', 'Bajkonur_g')
    AND arch_date2>='2018-01-01' AND arch_date2<='2019-01-01'
order by "region" LIMIT 1;