coffeemonitor
coffeemonitor

Reputation: 13120

MySQL - Optimizing OR statement

I want to search 3 columns using the OR clause. I'm missing something simply, I know, but I keep getting a mysql error.

Here's what I have so far:

SELECT customerid,companyname,firstname,lastname
FROM `tbl_customers` 
WHERE customeronoff = 1 
AND customerrecordtype = 'A' 
AND (companyname LIKE '$query%') OR (lastname LIKE '$query%') OR (firstname LIKE '$query%')   
ORDER BY lastname ASC

I must be placing the OR's wrong. Would someone fix me, please

Upvotes: 1

Views: 185

Answers (2)

You're missing two parentheses:

SELECT customerid,companyname,firstname,lastname
FROM `tbl_customers` 
WHERE customeronoff = 1 
AND customerrecordtype = 'A' 
AND **(**(companyname LIKE '$query%') OR (lastname LIKE '$query%') OR (firstname LIKE '$query%')**)**
ORDER BY lastname ASC

Upvotes: 1

John Conde
John Conde

Reputation: 219794

Use paranethesis to group your OR staements:

AND (
     (companyname LIKE '$query%') 
  OR (lastname LIKE '$query%') 
  OR (firstname LIKE '$query%')  
)

Upvotes: 3

Related Questions