Reputation: 167
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
Upvotes: 0
Views: 4003
Reputation: 183456
It sounds like you want this:
SELECT *
FROM pharmacy_items
LEFT
OUTER
JOIN pharmacy_quantity_types
ON pharmacy_items.quantity_type = pharmacy_quantity_types.id
WHERE pharmacy_items.name LIKE '%query_here%'
OR pharmacy_items.description LIKE '%query_here%'
where the restrictions on pharmacy_items
records are in a WHERE
clause rather than in a LEFT OUTER JOIN
's ON
clause.
(Also note:
AND
has higher precedence than OR
, so a AND b OR C
means (a AND b) OR c
, whereas I think you wanted a AND (b OR C)
. The above query fixes this implicitly, by moving b OR c
into a WHERE
clause, so it's separated from a
anyway.'...'
is a literal string, so 'pharmacy_items.name'
means "the actual string pharmacy_items.name
", which is not the same as "the name
field of the pharmacy_items
record". The latter is written pharmacy_items.name
or `pharmacy_items`.`name`
.))
Upvotes: 3