SQL中的AND OR子句

时间:2015-12-28 09:50:51

标签: sql sql-server

我想写一个这样的查询:

SELECT * FROM db WHERE ID = id AND Text != text OR Text = text

我的意思是ID = id子句和Text != text子句应该和,,并且它们应该与 OR 结合使用最后一个子句。我怎样才能做到这一点?感谢。

6 个答案:

答案 0 :(得分:5)

SELECT * FROM db WHERE (ID = id AND Text != text) OR Text = text

在合并andor

时,您应始终使用括号

答案 1 :(得分:3)

SELECT * FROM db WHERE (ID = id AND Text != text) OR Text = text

使用括号分隔两个子句

答案 2 :(得分:1)

SELECT *
FROM   db
WHERE  (ID = id AND TEXT != TEXT)
       OR 
       OR TEXT = TEXT

答案 3 :(得分:1)

SELECT * FROM db WHERE (ID = id AND Text != text) OR Text = text

答案 4 :(得分:0)

USE逻辑运算符(AND / OR):

SELECT * FROM db WHERE (ID = id AND Text != text) OR Text = text

或者您可以使用CASE:

SELECT * FROM db where 
(CASE WHEN ID = id THEN (CASE WHEN Text != text THEN 1 ELSE 0 END) ELSE 0 end = 1) OR
(CASE WHEN Text = text THEN 1 ELSE 0 END) = 1

答案 5 :(得分:0)

试试这个: SELECT * FROM db WHERE(ID = id AND Text!= text)或Text = text