Error in SQL result

2

Well, this is what I'm doing, I'm having to do a select in a database, where I should look for values that exist between two dates, and that have a specific user. I made the select like this:

SELECT * FROM 'tabela' WHERE 'data' BETWEEN 'dataInicio' AND 'dataFim' AND 'usuarioID' = 0 OR 'adminID' = 2

With this I should appear as a result 2 records containing the user adminID = 2 in the searched period (I threw random values to test). Only instead of appearing 2 records, it returns all the records that the adminID is, regardless of the date search interval. I tested the direct command on the MySql database, and if I split the query into

SELECT * FROM 'tabela' WHERE 'data' BETWEEN 'dataInicio' AND 'dataFim'

and

SELECT * FROM 'tabela' WHERE 'usuarioID' = 0 OR 'adminID' = 2

Both are working properly, what can be happening when I join them together?

PS: Now that I've started to learn the database, then if I did something sooooooo dumb, disregard it please.

    
asked by anonymous 31.05.2017 / 21:01

2 answers

2

The problem is that you should isolate the OR clause from your query :

SELECT *
  FROM 'tabela'
 WHERE 'data' BETWEEN 'dataInicio' AND 'dataFim'
   AND ('usuarioID' = 0 OR 'adminID' = 2)
    
31.05.2017 / 21:04
2

Just as in mathematics you have to say which operation has the highest priority, this is done through parentheses.

Your query should look like this:

SELECT * FROM 'tabela' WHERE
'data' BETWEEN 'dataInicio' AND 'dataFim' AND ('usuarioID' = 0 OR 'adminID' = 2)

This ensures that the date range will be respected. And only users with id zerou or two respect the entire condition.

    
31.05.2017 / 21:04