2

I'm new to PHP and I'm trying to select records (for search functionality) in my table where the month is static and other columns vary.

Below is the query:

SELECT * 
FROM issue 
WHERE month = "Apr 2019" 
    AND issue LIKE "%ekh%" 
    OR issue_type LIKE "%ekh%" 
    OR facility LIKE "%ekh%" 
    OR issue_id LIKE "%ekh%" 
    OR priority LIKE "%ekh%" 
ORDER BY issue_id DESC

This is rather returning all rows that satisfy the like clauses, even when month isnt = "Apr 2019".

2
  • Put all the like statements inside parentheses, so you have month="XX" and (issues like "XX" etc). Commented Apr 9, 2019 at 21:54
  • 1
    Fix your parentheses. Commented Apr 9, 2019 at 21:54

2 Answers 2

3

In algebra, the AND operation is done before the OR operation. This is the same rule in your WHERE clause.

You can fix this with parentheses like this :

SELECT *
FROM issue
WHERE month = "Apr 2019"
    AND (issue LIKE "%ekh%"
        OR issue_type LIKE "%ekh%"
        OR facility LIKE "%ekh%"
        OR issue_id LIKE "%ekh%"
        OR priority LIKE "%ekh%")
ORDER BY issue_id DESC
Sign up to request clarification or add additional context in comments.

Comments

1

When mysql hits first or it automatically returns everything because or something is true. Therefore you should use parentheses:

SELECT *
FROM issue
WHERE month = "Apr 2019" AND
(issue like "%ekh%" OR
 issue_type like "%ekh%" OR
 facility like "%ekh%" OR
 issue_id like "%ekh%" OR
 priority like "%ekh%")
ORDER BY issue_id DESC

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.