mysql LIKE搜索不适用于带空格的文本

时间:2015-09-23 16:27:07

标签: php mysql

我对我的cms有以下查询,我用它根据用户提供的搜索查询查找帖子:

"SELECT post_content FROM c_posts WHERE post_content LIKE '%$s%' OR post_title LIKE '%$s%' OR post_description LIKE '%$s%' OR link_title LIKE '%$s%' OR tags LIKE '%$s%' AND post_status <> 'Initialized'";

当查询$s是一个像 &#39;但如果$s包含任何类似的空格,它就不会返回任何内容,例如其他内容&#39;或&#39;东西&#39; 即可。我需要搜索确切的单词。所以我无法修剪空间。怎么处理这个? (由于性能问题,我决定不使用FULLTEXT)

2 个答案:

答案 0 :(得分:1)

在查看您的代码之后,我认为您可能遇到过与我自己的网站类似的问题:执行&#39; AND&&#39; OR&#39;秒。以下是一些可能有帮助的链接。

SQL Server ANDs and ORs precedence

http://www.bennadel.com/blog/70-sql-query-order-of-operations.htm

使用括号尝试:

SELECT post_content 
FROM c_posts 
WHERE (post_content LIKE '%$s%' OR post_title LIKE '%$s%' OR post_description LIKE '%$s%' OR link_title LIKE '%$s%' OR tags LIKE '%$s%') 
AND post_status <> 'Initialized'

答案 1 :(得分:0)

您的查询中存在两个问题:

1)$ sign以特定方式管理,请查看此帖子以获取更多答案:MySQL search for "$" (dollar sign) fails?

2)你应该用括号

括起OR
SELECT post_content FROM c_posts WHERE 
  (post_content LIKE '%$s%' 
    OR post_title LIKE '%$s%' 
    OR post_description LIKE '%$s%' 
    OR link_title LIKE '%$s%' 
    OR tags LIKE '%$s%')
  AND post_status <> 'Initialized'

这样查询会在其中一个post_status中搜索$ s,如果找到,则在状态与“已初始化”不同时获取所有帖子

使用您的代码,而不是返回错误的结果,使用和tagstags计算查询搜索其中一个,但最后一个(post_status)。 ,所以它将返回所有帖子,标题描述等匹配,但状态是无关的......

相关问题