I’m creating a search function. My sql query uses LIKE and OR LIKE in the where clause. One of the fields in the table I’m searching in is called quantity_types where it stores only codes that corresponds to the values found in another table. So to retrieve the values from the other, I want to use a Left Outer Join in my query.
Here’s my sample code:
SELECT * FROM `pharmacy_items`
LEFT OUTER JOIN pharmacy_quantity_types
ON pharmacy_items.quantity_type = pharmacy_quantity_types.id
AND 'pharmacy_items.name' LIKE '%query_here%'
OR 'pharmacy_items.description' LIKE '%query_here%'
This query returns all the records in my pharmacy_items table instead of those records which are supposed to be returned with I’m not using a LEFT OUTER JOIN.
How would I build my query such that the returned results are those that satisfies first the WHERE clause before the LEFT OUTER JOIN
It sounds like you want this:
where the restrictions on
pharmacy_itemsrecords are in aWHEREclause rather than in aLEFT OUTER JOIN‘sONclause.(Also note:
ANDhas higher precedence thanOR, soa AND b OR Cmeans(a AND b) OR c, whereas I think you wanteda AND (b OR C). The above query fixes this implicitly, by movingb OR cinto aWHEREclause, so it’s separated fromaanyway.'...'is a literal string, so'pharmacy_items.name'means “the actual stringpharmacy_items.name“, which is not the same as “thenamefield of thepharmacy_itemsrecord”. The latter is writtenpharmacy_items.nameor`pharmacy_items`.`name`.))