Jazerix
Jazerix

Reputation: 4801

MySQL Using LIKE, AND, OR together

I'm creating a search function that search for some pictures. Each picture has a state, that says if it is approved or rejected. The mysql checks for the state before returning, however it still returns images, that should not be returned.

Here is my query:

SELECT * FROM Pictures
WHERE ImageTitle LIKE '%yaa%'
OR ImageDescription LIKE '%yaa%'
AND Approval='Approved'
Order BY DateTime DESC

"yaa" is the search for now. It's only an example. The query returns a result that is marked as approved, but also a result marked as rejected. What is wrong with my query?

I've tried moving the AND statement to the start of the query, returns the same.

Upvotes: 0

Views: 3299

Answers (2)

Ankit Gupta
Ankit Gupta

Reputation: 189

/*There should be a parenthesis for 'or' condition, and the state condition should remain outside of the parenthesis*/
SELECT * FROM Pictures
WHERE (ImageTitle LIKE '%yaa%'
OR ImageDescription LIKE '%yaa%')
AND Approval='Approved'
Order BY DateTime DESC

Upvotes: 1

John Woo
John Woo

Reputation: 263713

Group your OR condition with parenthesis.

SELECT * 
FROM Pictures
WHERE (ImageTitle LIKE '%yaa%'
       OR ImageDescription LIKE '%yaa%')
       AND Approval='Approved'
Order BY DateTime DESC

Upvotes: 8

Related Questions