SQL AND OR 查询
Posted
技术标签:
【中文标题】SQL AND OR 查询【英文标题】:SQL AND OR query 【发布时间】:2015-03-25 22:10:12 【问题描述】:我正在尝试从我们的客户服务查询中选择一些消息,其中 Mmessage 所有者是 ABC,数据是 LIKE ABCDEF AND message ... 并且消息是从客户到 CSservice 或从 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
【问题讨论】:
对于 jergen d 的答案加 1,您只需要在 OR 条件周围加上一组括号。 【参考方案1】: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
【讨论】:
非常感谢。实际上我在发布消息几秒钟后就知道了这一点:) 还在学习 SQL :)【参考方案2】:您的查询基本正确。但是您必须考虑到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;
【讨论】:
以上是关于SQL AND OR 查询的主要内容,如果未能解决你的问题,请参考以下文章