-1

So I have the following mysql query, which works but not the right way:

SELECT *
FROM (`CriteriaItems`)
INNER JOIN `Address` 
  ON `Address`.`address_id` = `CriteriaItems`.`address_id`
WHERE `criteria_id` = '2'
  AND `status` = 'published'
  AND `mls_id` LIKE '%123%'
  OR `Address`.`address` LIKE '%123%'
LIMIT 10

The problem is that I see it returns results that also have "status" = "deleted" and thats because of ``Address.addressLIKE '%123%' if I remove this it works, but I need this.

So it suposed to search in the address table as well, but only based on CriteriaItems`.`address_id

Uffo
  • 9,628
  • 24
  • 90
  • 154

2 Answers2

3

Its because AND operator has higher precedence than OR, right now your query works like this.

WHERE `criteria_id` = '2' 
AND (`status` = 'published' AND `mls_id` LIKE '%123%') 
OR `Address`.`address` LIKE '%123%' LIMIT 10

More information on this can be found here

So you need to use Parenthesis to apply the condition properly

WHERE `criteria_id` = '2' 
AND `status` = 'published' AND 
(`mls_id` LIKE '%123%' OR `Address`.`address` LIKE '%123%')
LIMIT 10
Community
  • 1
  • 1
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
1

You need to wrap OR with bracket:

SELECT * 
FROM `CriteriaItems`
JOIN `Address` 
  ON `Address`.`address_id` = `CriteriaItems`.`address_id` 
WHERE `criteria_id` = '2' 
  AND `status` = 'published' 
  AND (`mls_id` LIKE '%123%' OR `Address`.`address` LIKE '%123%')
LIMIT 10;

Consider also using ORDER BY to get stable results.

Simple bool logic:

p1 AND p2 AND p3 OR p4 is true <=> (p1 AND p2 AND p3) is true OR p4 is true

I guess you want:

p1 AND p2 AND (p3 OR p4)
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275