MySQL查询仅返回status='Y'数据的问题排查与解决
解决你的MySQL查询逻辑问题
嘿,这个问题很常见,是逻辑运算符优先级在搞鬼!
你原来的查询语句:
select * from table where status='Y' and keywords like '%cook%' OR category like '%cook%' OR product_name like '%cook%'
在MySQL里,AND的优先级比OR高,所以它会被解析成这样:
select * from table where (status='Y' and keywords like '%cook%') OR category like '%cook%' OR product_name like '%cook%'
这就意味着,只要满足category like '%cook%'或者product_name like '%cook%',不管status是不是'Y',都会被返回——这就是为什么你会看到status='N'的记录。
修正方法
把所有OR连接的模糊查询条件用括号括起来,让它们成为一个整体,再和status='Y'用AND关联,这样就能保证只返回status为'Y'的记录了:
select * from table where status='Y' and (keywords like '%cook%' OR category like '%cook%' OR product_name like '%cook%');
这样修改后,查询逻辑就变成了:status必须是'Y',同时keywords、category、product_name三个字段中至少有一个包含'cook',完全符合你的需求。
内容的提问来源于stack exchange,提问作者Chandan Jha
相关产品推荐
相关产品推荐

