简体   繁体   English

MySQL查询不符合条件

[英]Mysql query doesn't follow condition

So I have the following mysql query, which works but not the right way: 因此,我有以下mysql查询,该查询有效,但方法不正确:

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 . 问题是我看到它返回的结果也具有“ status” =“ deleted”,这就是因为“ Address” . address LIKE '%123%' if I remove this it works, but I need this. 如果我删除了此地址,则LIKE '%123%' ,但是我需要它。

So it suposed to search in the address table as well, but only based on CriteriaItems`.`address_id 因此它也想在地址表中进行搜索,但仅基于CriteriaItems`.`address_id

Its because AND operator has higher precedence than OR , right now your query works like this. 这是因为AND运算符的优先级比OR更高,现在您的查询像这样工作。

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

You need to wrap OR with bracket: 您需要使用方括号将OR换行:

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. 还考虑使用ORDER BY获得稳定的结果。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM