如何在sql中一起使用OR / AND运算符?

时间:2013-10-19 17:50:57

标签: sql tsql

我遇到问题让这个查询起作用,我实际上是在尝试同时使用OR和AND运算符,但似乎无法弄清楚为什么我收到此错误的问题“:"expecting ABSOLUTE'或ACTION' or ADD'或ALL' or ALTER'“`。这是我的sql代码:

SELECT * 
FROM EDXW ED, TRANSACTION TXN
WHERE ED.LAM_BK like 'TAR%'
AND ED.KEY = TXN.KEY
AND substring(ED.JAM_BK from position('~' in ED.JAM_BK) + 1) = TXN.EBS_ID

(AND ED.CLS_CD IN ('WIS','OP','OPP')
AND TXN.REV_CD IN ('0360','0361')
AND TXN.LS_CTR_CD IN ('548000','552000','552500','553000','553500','554000','555000','555500','558000')
AND ED.SITE_CD = 'X' )

OR

( ED.ED_CLS_CD IN ('WIS','OP','OPP')
AND AND TXN.REV_CD IN ('0350','0311')
AND AND TXN.LS_CTR_CD IN ('548000','558300')
AND LOC.ED_SITE_CD = 'M')

OR

( ED.ED_CLS_CD IN ('WIS','OP','OPP')
AND AND TXN.REV_CD IN ('0350','0311')
AND AND TXN.LS_CTR_CD IN ('549000','557300')
AND LOC.ED_SITE_CD IN ('M','K'));

2 个答案:

答案 0 :(得分:2)

你有额外的parens或遗失和/或。这是一个显示问题的简化版本:

SELECT * 
FROM tables
WHERE clause1
(AND clause2)

从SQL的角度来看,这是不正确的。

可能是正确的版本
SELECT * 
FROM tables
WHERE clause1
AND (clause2)

SELECT * 
FROM tables
WHERE clause1
OR (clause2)

看到区别? parens集团的声明。所以你可以有更复杂的表达式,如:     选择 *     FROM表     WHERE子句1     AND(第2条或第3条)

他们的关键是,如果你要将parens中的所有内容减少为单个true / false值,那么查询仍然有意义。

答案 1 :(得分:2)

我认为问题在于你说:a and b and c and d or e or f但我想你想说a and b and c and (d or e or f)这是非常不同的。当f为真或e为真时,整个表达式变为真。大括号说清楚。我认为您的选择必须如下所示:

SELECT * 
FROM EDXW ED, TRANSACTION TXN
WHERE ED.LAM_BK like 'TAR%'
AND ED.KEY = TXN.KEY
AND substring(ED.JAM_BK from position('~' in ED.JAM_BK) + 1) = TXN.EBS_ID
AND
(
 (ED.CLS_CD IN ('WIS','OP','OPP')
 AND TXN.REV_CD IN ('0360','0361')
 AND TXN.LS_CTR_CD IN ('548000','552000','552500','553000','553500','554000','555000','555500','558000') 
 AND ED.SITE_CD = 'X' )

OR

 ( ED.ED_CLS_CD IN ('WIS','OP','OPP')
 AND TXN.REV_CD IN ('0350','0311')
 AND TXN.LS_CTR_CD IN ('548000','558300')
 AND LOC.ED_SITE_CD = 'M')

OR

 ( ED.ED_CLS_CD IN ('WIS','OP','OPP')
 AND TXN.REV_CD IN ('0350','0311')
 AND TXN.LS_CTR_CD IN ('549000','557300')
 AND LOC.ED_SITE_CD IN ('M','K'))
);