如何在选择查询中一起使用“AND”和“OR”关键字?

时间:2011-01-06 12:57:12

标签: mysql

T有一个选择查询

 SELECT * FROM tbl_docuserstatus WHERE doc_id='1' 
AND doc_midlvluser = '1' AND 
(docstatus_id != '4' OR docstatus_id != '5' OR docstatus_id != '8' OR docstatus_id != '0')

但结果似乎不适用于(docstatus_id != '4' OR docstatus_id != '5' OR docstatus_id != '8' OR docstatus_id != '0')部分。

我需要查询才能显示所有值为docid = 1和doc_midlvluser = 1且dostatus_id不等于4或5或8或0的值

请帮帮我怎么用?

2 个答案:

答案 0 :(得分:3)

使用:

SELECT * FROM tbl_docuserstatus WHERE doc_id='1' 
AND doc_midlvluser = '1' AND 
(docstatus_id != '4' AND docstatus_id != '5' 
 AND docstatus_id != '8' AND docstatus_id != '0')

或者只是应用DeMorgan定理,因此编码和阅读更容易:

SELECT * FROM tbl_docuserstatus WHERE doc_id='1' 
AND doc_midlvluser = '1' AND 
NOT (docstatus_id = '4' OR docstatus_id = '5' 
     OR docstatus_id = '8' OR docstatus_id = '0')

或者更好的是,使用IN:

SELECT * FROM tbl_docuserstatus WHERE doc_id='1' 
AND doc_midlvluser = '1' AND 
   docstatus_id NOT IN ('4','5','8','0')

与此相关:https://stackoverflow.com/questions/130965/what-is-the-worst-code-youve-ever-written/311377#311377

而且:Is it acceptable to only use the 'else' portion of an 'if-else' statement?

答案 1 :(得分:0)

您的OR条款是互斥的:

如果docstatus_id = 4,那么根据该条款的第一部分它无效,但IS对其余部分有效。

也许你应该使用docstatus_id而不是('4','5','8','0'),如果那是你想要达到的目的。