SQL - 组合 AND & OR

SQL - Combining AND & OR

我有以下代码:

SELECT sdd.sd_doc_classification,
       sdd.sd_title,
       sdd.sd_desc,
       sdr.sd_upload_fname
FROM sdoc_docs AS sdd
INNER JOIN sdoc_revh AS sdr ON sdd.sd_id = sdr.sd_id
WHERE (sdd.sd_title LIKE '%policy%')
    OR (sdd.sd_title LIKE '%guideline%')
    AND (sdd.sd_doc_classification NOT LIKE '%\Trust Wide Policies & Guidelines\%')

但是,添加“OR (sdd.sd_title LIKE '%guideline%')”已将其破坏,并且语句现在 returns 值 类似 '%\Trust Wide Policies & Guidelines\%'

代码在删除上面的指南示例后按预期运行。

本质上,我想显示任何具有 sd_title(如 policyguideline 且不具有 sd_doc_classification(如 '%trust wide pol%')的任何内容。

正如 Gordon 和 dnoeth 所指出的,您的括号是问题所在。我认为您实际上需要以下查询。

SELECT sdd.sd_doc_classification,
       sdd.sd_title,
       sdd.sd_desc,
       sdr.sd_upload_fname
FROM sdoc_docs AS sdd
INNER JOIN sdoc_revh AS sdr ON sdd.sd_id = sdr.sd_id
WHERE 
    (
        sdd.sd_title LIKE '%policy%'
        OR 
        sdd.sd_title LIKE '%guideline%'
    )
    AND 
    sdd.sd_doc_classification NOT LIKE '%\Trust Wide Policies & Guidelines\%'

我发现正确地标记出不同的 OR 和 AND 子句显然使它们更容易形象化和理解。

AND 的优先级高于 OR - 即,就好像您是这样编写查询的:

SELECT sdd.sd_doc_classification,
       sdd.sd_title,
       sdd.sd_desc,
       sdr.sd_upload_fname
FROM       sdoc_docs AS sdd
INNER JOIN sdoc_revh AS sdr ON sdd.sd_id = sdr.sd_id
WHERE      (sdd.sd_title LIKE '%policy%') OR 
           ((sdd.sd_title LIKE '%guideline%') AND 
            (sdd.sd_doc_classification NOT LIKE 
             '%\Trust Wide Policies & Guidelines\%')) 

如果你想控制条件被评估的优先级,你可以自己明确地添加括号:

SELECT sdd.sd_doc_classification,
       sdd.sd_title,
       sdd.sd_desc,
       sdr.sd_upload_fname
FROM       sdoc_docs AS sdd
INNER JOIN sdoc_revh AS sdr ON sdd.sd_id = sdr.sd_id
WHERE      ((sdd.sd_title LIKE '%policy%') OR 
            (sdd.sd_title LIKE '%guideline%')) AND 
           (sdd.sd_doc_classification NOT LIKE 
             '%\Trust Wide Policies & Guidelines\%')