简体   繁体   English

如何使用LIKE忽略mysql搜索查询中的空格?

[英]How can I ignore spaces in mysql search query with LIKE?

I am working on a program where a user searches for a "course" by course code or name. 我正在开发一个程序,其中用户通过课程代码或名称搜索“课程”。 I am trying to make it so if the user searches "CODE1002", CODE 1002 EL from the database will still return (there is a space). 我正在尝试这样做,如果用户搜索“ CODE1002”,则数据库中的CODE 1002 EL仍然会返回(有空格)。 As indicated by other posts I have tried to use the REPLACE function with no success. 如其他帖子所述,我尝试使用REPLACE函数没有成功。

Here is my current code (however it does not ignore spaces): 这是我当前的代码(但是它不会忽略空格):

$records = $conn->prepare('SELECT (SELECT COUNT(*) FROM courses WHERE (course_code LIKE :searchText OR course_name LIKE :searchText)) AS course_count, course_id, course_code, course_name FROM courses WHERE (course_code LIKE :searchText OR course_name LIKE :searchText) ORDER BY course_code LIMIT 6');

$final_search_term = "%".$search_term."%";
$records->bindParam(':searchText', $final_search_term);

Here is my attempt at adding REPLACE to ignore spaces on the course_code with no success: 这是我尝试添加REPLACE以忽略Course_code上的空格而没有成功的尝试:

$records = $conn->prepare('SELECT (SELECT COUNT(*) FROM courses WHERE (REPLACE(course_code,' ','') LIKE :searchText OR course_name LIKE :searchText)) AS course_count, course_id, course_code, course_name FROM courses WHERE (REPLACE(course_code,' ','') LIKE :searchText OR course_name LIKE :searchText) ORDER BY course_code LIMIT 6');

$final_search_term = "%".$search_term."%";
$records->bindParam(':searchText', $final_search_term);

The first code works perfectly aside from not ignoring spaces. 除了不忽略空格外,第一个代码还可以完美地工作。

You are putting the replace on the wrong side. 您将替换放在错误的一侧。 Just to be safe, let's do it for both operands: 为了安全起见,让我们对两个操作数都这样做:

REPLACE(course_code, ' ', '') LIKE REPLACE(:searchText, ' ', '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM