所以我有以下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
问题是我看到它返回的结果也有“status”=“已删除”,那就是因为``地址.
地址LIKE '%123%'
如果我删除它有效,但我需要此
因此,它也可以在地址表中搜索,但仅基于CriteriaItems`.`address_id
答案 0 :(得分:3)
因为AND
运算符的优先级高于OR
,所以现在您的查询的工作方式与此类似。
WHERE `criteria_id` = '2'
AND (`status` = 'published' AND `mls_id` LIKE '%123%')
OR `Address`.`address` LIKE '%123%' LIMIT 10
有关此内容的更多信息,请访问here
因此,您需要使用括号来正确应用条件
WHERE `criteria_id` = '2'
AND `status` = 'published' AND
(`mls_id` LIKE '%123%' OR `Address`.`address` LIKE '%123%')
LIMIT 10
答案 1 :(得分:1)
您需要使用括号
包装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;
还要考虑使用ORDER BY
来获得稳定的结果。
简单的布尔逻辑:
p1 AND p2 AND p3 OR p4 is true <=> (p1 AND p2 AND p3) is true OR p4 is true
我想你想要:
p1 AND p2 AND (p3 OR p4)