MySQL中如何在使用LIKE搜索语句的同时使用OR语句
我正在尝试创建一个很好的小搜索语句,根据返回的内容使用不同的搜索词来搜索多个字段。我基本上设置了一个顺序,如果找不到一个搜索词,请尝试下一个搜索词。不过,我使用 WHERE 子句来仅搜索一种类型的数据。目前我收到一些奇怪的结果返回,因为我认为我的订单不正确,似乎我的 WHERE 子句被忽略。
这是我的声明(我使用 PHP):
mysql_query("SELECT * FROM item AS i LEFT JOIN country AS c ON i.country_id = c.country_id WHERE i.item_status = 'active' AND (i.item_name LIKE '%".$_SESSION['item']."%') OR i.item_description LIKE '%".$_SESSION['description']."%' OR i.item_name LIKE '%".$_SESSION['description']."%' ");
提前谢谢您。
I am trying to create a good little search statement that searches muitple fields using the with different search terms depending on what is returned. I am basiclly setting an order in which I want to search if one search term is not found try the next one. However I am using a WHERE clause to seperate search only one type of data. Currently I am getting some strange results returned because I don't think my order is correct, it seems that my WHERE clause is being ignored.
here is my statement (I am usig PHP):
mysql_query("SELECT * FROM item AS i LEFT JOIN country AS c ON i.country_id = c.country_id WHERE i.item_status = 'active' AND (i.item_name LIKE '%".$_SESSION['item']."%') OR i.item_description LIKE '%".$_SESSION['description']."%' OR i.item_name LIKE '%".$_SESSION['description']."%' ");
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不使用全文搜索功能?
需要更改表结构以创建全文搜索索引。
然后您的查询就会变得:
简单、准确且更快。
Why don't you use full-text search feature?
Need to alter table structure for create fulltext search index.
Then your queries turns to:
Simple, accurate, and faster.
将右括号移至语句末尾:
Move the right parenthesis to the end of the statement:
这是你的括号放错地方了。这是正确的代码:
It is your parentheses in the wrong place. Here is the correct code:
OR 运算符的优先级低于 AND 运算符。 http://dev.mysql.com/doc/refman/4.1 /en/operator-precedence.html
将所有 OR 放在括号内(包含所有 OR 的一个,而不是每个 OR 一个;))。
The OR operator has lower precedence than the AND operator. http://dev.mysql.com/doc/refman/4.1/en/operator-precedence.html
Put all the ORs inside parentheses (one that contains all of them, not one for each of them ;) ).