Reputation:
I'm trying to SELECT
from this database WHERE
either statement_from
OR username
is = to $username
however this isn't working correctly. I have looked at previously asked similar questions however unsure how to implement the previous answers into this query.
"SELECT * FROM `usr_statements` WHERE `statement_from` = '$username'
OR `username` = '$username' AND `statement_timestamp` > '$start_date'
AND `statement_timestamp` < '$end_date' ORDER BY `statement_ref` DESC"
What I'm trying to achieve is to select all the results in the database where the statement_from
or the username
is = to $username
.
Upvotes: 4
Views: 1201
Reputation: 93694
Currently your query is validated like this
WHERE `statement_from` = '$username'
OR (`username` = '$username' AND `statement_timestamp` > '$start_date')
AND `statement_timestamp` < '$end_date'
because AND
has higher precedence than OR
so AND
will be evaluated first.
You need to add proper parenthesis
SELECT * FROM `usr_statements`
WHERE (`statement_from` = '$username'
OR `username` = '$username')
AND `statement_timestamp` > '$start_date'
AND `statement_timestamp` < '$end_date'
ORDER BY `statement_ref` DESC
Also you can use IN
operator to do this as mentioned by Jarlh in comments
SELECT * FROM `usr_statements`
WHERE $username in (statement_from, username)
AND `statement_timestamp` > '$start_date'
AND `statement_timestamp` < '$end_date'
ORDER BY `statement_ref` DESC
Upvotes: 7
Reputation: 35780
The precedence of operators is NOT
-> AND
-> OR
, so you need some parentesis here:
"SELECT * FROM `usr_statements` WHERE (`statement_from` = '$username'
OR `username` = '$username') AND `statement_timestamp` > '$start_date'
AND `statement_timestamp` < '$end_date' ORDER BY `statement_ref` DESC"
Upvotes: 0