OR returns result not expected

1

I'm running this function

SELECT COUNT(id) FROM 'system_stats' WHERE  'name' = 1 OR 0 AND 'us_id' = 0

It returns a value equal to 1, but this 1 does not, when I execute separately in that way, it returns me 0, why with OR does it return 1?

SELECT COUNT(id) FROM 'system_stats' WHERE  'name' = 1 AND 'us_id' = 0
SELECT COUNT(id) FROM 'system_stats' WHERE  'name' = 0 AND 'us_id' = 0
    
asked by anonymous 29.12.2014 / 02:20

1 answer

4

Returns this way because you are sending it. OR can not be used loosely so it is not natural language text.

SELECT COUNT(id) FROM 'system_stats' WHERE  'name' = 1 OR 0 AND 'us_id' = 0

name = 1 according to you, gives false.

0 gives true since this is a statement.

us_id = 0 should be giving true

0 AND us_id = 0 gives true. This subexpression is executed first by the precedence rule. It's like a multiplication in arithmetic.

False or true, give true, then return something you do not want.

This is called Boolean algebra . If you do not understand this you will not be able to program.

Probably what you wanted to do is this:

SELECT COUNT(id) FROM 'system_stats' WHERE ('name' = 1 OR 'name' = 0) AND 'us_id' = 0

Understanding operator precedence is very important. You have to understand what you do before. Just as knowing that the product takes precedence over the sum, you have to know that AND takes precedence over OR and if you want to associate the two terms of OR before taking one of them and associate with the other term of the AND has to make this explicit in the code through parentheses.

Otherwise, if the problem is otherwise your logic is even more confusing. Your question does not make it very clear what you really want. You need to learn to express yourself well in and outside the program to achieve the results you expect.

    
29.12.2014 / 02:28