Error in SQL output

Asked

Viewed 45 times

2

Guys, here’s the thing, I’m having to do a select in a bank, where I should look for values that exist between two dates, and that have a specific user. I made the select so:

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

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

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

and

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

both are working properly, which may be happening when I put them together?

PS: Now that I’ve started learning databases, then if I’ve done something really stupid, please disregard it.

2 answers

2


The problem is that you must isolate the clause OR of his query:

SELECT *
  FROM `tabela`
 WHERE `data` BETWEEN 'dataInicio' AND 'dataFim'
   AND (`usuarioID` = 0 OR `adminID` = 2)
  • Thanks, I really hadn’t thought of that. Thank you

2

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

Your consultation 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 zeroed or two respect all condition.

  • Thanks, I really hadn’t thought of that. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.