我在SQL Server 2012上选择查询,其中有多个where条件,这是我的代码:
SELECT *
FROM ##TempGet a
LEFT JOIN Techs b ON a.TECH = b.TechID
--LEFT JOIN (SELECT * FROM OPENQUERY (Serv, 'SELECT * FROM Hist order by histdate desc')) as c on a.CUST_ACCT = c.CUST_ACCT and c.HISTDATE >= a.sch_date
LEFT JOIN (SELECT ParamId, ParamType, Value1, Value2, Value3, Status, UpdateBy, UpdateDate FROM Parameter AS Parameter_3 WHERE (ParamType = 'SCABranch')) AS p ON LEFT (SCHAREAS, 1) = p.Value1
WHERE WSTAT = 'P/TC'
AND (a.CUST_ACCT NOT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM NOT IN (SELECT OFFERNUM from TC))
OR (a.CUST_ACCT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM IN (SELECT OFFERNUM from TC ) and a.sch_date not in (SELECT SCH_DATE from TC where CUST_ACCT = a.CUST_ACCT and OFFERNUM = a.Offernum))
OR (a.CUST_ACCT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM NOT IN (SELECT OFFERNUM from TC ) and a.sch_date not in (SELECT SCH_DATE from TC where CUST_ACCT = a.CUST_ACCT and OFFERNUM = a.Offernum))
主要发布是法规太复杂的地方,
WHERE WSTAT = 'P/TC'
AND (a.CUST_ACCT NOT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM NOT IN (SELECT OFFERNUM from TC))
OR (a.CUST_ACCT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM IN (SELECT OFFERNUM from TC ) and a.sch_date not in (SELECT SCH_DATE from TC where CUST_ACCT = a.CUST_ACCT and OFFERNUM = a.Offernum))
OR (a.CUST_ACCT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM NOT IN (SELECT OFFERNUM from TC ) and a.sch_date not in (SELECT SCH_DATE from TC where CUST_ACCT = a.CUST_ACCT and OFFERNUM = a.Offernum))
是和它结合还是真的?因为我选择的某些数据不会显示,但它应该在那里显示。
答案 0 :(得分:1)
无论
你的括号是对的吗?在这三行中,您打算对这三行进行“或”操作吗?例如。如果WSTAT ='P / TC'应该只应用接下来的三行中的一行?如果是这样,请在括号中包含3
WHERE WSTAT = 'P/TC'
AND ( -- added bracket
(a.CUST_ACCT NOT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM NOT IN (SELECT OFFERNUM from TC))
OR (a.CUST_ACCT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM IN (SELECT OFFERNUM from TC ) and a.sch_date not in (SELECT SCH_DATE from TC where CUST_ACCT = a.CUST_ACCT and OFFERNUM = a.Offernum))
OR (a.CUST_ACCT IN (SELECT CUST_ACCT FROM TC) AND a.OFFERNUM NOT IN (SELECT OFFERNUM from TC ) and a.sch_date not in (SELECT SCH_DATE from TC where CUST_ACCT = a.CUST_ACCT and OFFERNUM = a.Offernum))
) -- added bracket
这一切都归结为谓词。简单来说谓词是一个事实陈述,通常在查询的where部分(可以在其他地方完成 - 在INNER / OUTER的ON部分加入HAVING子句。)每个必须为true,并且只有每个谓词为真时才会你得到一个结果。所以你要问
Get me <the columns I've listed>
from <the tables I've listed>
where
predicate 1 -- something you've written
predicate 2 -- WHERE WSTAT = 'P/TC'
predicate 3 -- the AND line
predicate 4 -- the OR line
predicate 4 -- the other OR
我怀疑你想要
Get me <the columns I've listed>
from <the tables I've listed>
where
predicate 1 -- something you've written
predicate 2 -- WHERE WSTAT = 'P/TC'
predicate 3 -- the AND line or the first OR or the 2nd OR
或
对于这样的查询逻辑问题,有时它有助于注释掉查询的一部分,几乎总是一个where子句,以识别哪一个阻止了您的预期数据被返回。然后深入讨论相关部分。