SQL - Trouble with simple select query
I'm having some trouble figuring out why the SQL query below isn't working ... when members_only
is set to 0, it's still showing them...
SELECT *
FROM reports
WHERE story = "1"
OR barebones = "1"
A开发者_开发技巧ND members_only = "1"
It depends on your data, but you may not be aware that AND
has higher precedence in SQL than OR
, so your query really evaluates to this:
SELECT *
FROM reports
WHERE story = '1'
OR (barebones = '1' AND members_only = '1')
Consider using different brackets per the other answers to explicitly declare your intentions
Use brackets to distinguish your clarify the WHERE-condition.
SELECT *
FROM reports
WHERE (story = '1' OR barebones = '1')
AND members_only = '1'
I would say because it reads the query as:
WHERE (story = '1') OR (barebones = '1' AND members_only = '1')
since story = '1'
, the condition is satisfied
OR clauses can be tricky - you often need to explicitly tell the query where it belongs. I assume, you want this:
WHERE (story = '1' OR barebones = '1') AND members_only = '1'
Missing parenthesis? Did you want to do something like this:
SELECT *
FROM reports
WHERE (story = "1" OR barebones = "1") AND members_only = "1"
You are missing parenthesis.
The following code will work, assuming members_only HAS to be "1", but only story or barebones has to be "1".
SELECT *
FROM reports
WHERE
(story = "1" OR barebones = "1")
AND members_only = "1"
You should read up on TSQL Operator Precedence
In your original code, assume the following:
- store = 1
- barebones = 1
- *members_only* = 0
Due to Operator Precedence, barebones and *members_only* is evaluated first, and evaluates to false.
Following this, the result of the first boolean evaluation (false
) (also known as The Right Side
) is compared to (story = "1"
) (also known as The Left Side
).
The Right Side
evaluates to false, but The Left Side
evaluates to true.
Since the final boolean compression uses the OR
operator, the end result is a TRUE
, thus that record is indeed returned, no matter the value of either barebones or *members_only*, since The Left Side
always evaluates to True.
精彩评论