SQL AND OR查询

时间:2015-01-27 10:19:31

标签: sql qsqlquery

我正在尝试从我们的客户服务查询中选择一些消息,WHERE Mmessage所有者是ABC,数据是LIKE ABCDEF和消息...... AND消息来自客户到CS服务或从CSservice到客户。

我该怎么做?

SELECT Date, From, To, Data 
FROM Ccustomers WITH (NoLock)
WHERE MSGowner = 'ABC' AND Data LIKE '%ABCDEF%' AND 
([From] ='Customer' AND [To] = 'CSservice') OR ([From] ='CSservice' AND [To] = 'Customer') 

ORDER by Date

2 个答案:

答案 0 :(得分:2)

SELECT Date, From, To, Data 
FROM Ccustomers WITH (NoLock)
WHERE MSGowner = 'ABC' 
AND Data LIKE '%ABCDEF%' 
AND 
(
   ([From] = 'Customer'  AND [To] = 'CSservice') OR 
   ([From] = 'CSservice' AND [To] = 'Customer')
)
ORDER by Date

答案 1 :(得分:0)

您的查询基本上是正确的。但您必须考虑and连接比or“更强”。要获得所需的输出,您需要设置括号。

试试这个:

SELECT Date, [From], [To], Data 
FROM Ccustomers WITH (NoLock)
WHERE MSGowner = 'ABC' 
AND Data LIKE '%ABCDEF%' 
AND (([From] = 'Customer'  AND [To] = 'CSservice') OR ([From] = 'CSservice' AND [To] = 'Customer'))
ORDER BY Date;