[英]How to use the OR statement in MySQL while using the LIKE search statement
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.
但是,我使用WHERE子句来单独搜索仅一种类型的数据。 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.
目前,我得到一些奇怪的结果,因为我认为我的订单不正确,似乎我的WHERE子句被忽略了。
here is my statement (I am usig PHP): 这是我的声明(我是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. 先感谢您。
Move the right parenthesis to the end of the statement: 将右括号移到语句的末尾:
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']."%')
It is your parentheses in the wrong place. 这是您在错误位置的括号。 Here is the correct code:
这是正确的代码:
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']."%')");
Why don't you use full-text search feature? 为什么不使用全文搜索功能?
Need to alter table structure for create fulltext search index. 需要更改表结构以创建全文本搜索索引。
ALTER TABLE item ADD FULLTEXT (item_name, item_description);
Then your queries turns to: 然后您的查询将变为:
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
MATCH (i.item_name, i.item_description)
AGAINST (" . $_SESSION['item'] . " " . $_SESSION['description'] . ");
");
Simple, accurate, and faster. 简单,准确,更快。
The OR operator has lower precedence than the AND operator. OR运算符的优先级低于AND运算符。 http://dev.mysql.com/doc/refman/4.1/en/operator-precedence.html
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 ;) ). 将所有OR放在括号内(一个包含所有OR,而不是每个括号;)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.