简体   繁体   English

具有特殊字符的MySql搜索

[英]MySql Search With Special Character

I searching records from database using MySql as - 我使用MySql从数据库中搜索记录为 -

SELECT * FROM tab WHERE col LIKE '%myvalue%';

This is working fine and showing all the records having myvalue . 这工作正常并显示具有myvalue所有记录。

Now the problem is i have some records like my'value , myva'lue , myval-ue and my-value And also want to include these records in search. 现在的问题是我有一些记录,如my'valuemyva'luemyval-uemy-value ,还想在搜索中包含这些记录。 Also when i search for my'value then it should show myvalue and my-value . 此外,当我搜索my'value那么它应该显示myvaluemy-value

How to achieve this? 怎么做到这一点? Any Help. 任何帮助。 Is it possible to do using LIKE operator? 是否可以使用LIKE运算符?

As you are using PHP you should do the following, if someone uses your search: 当您使用PHP时,如果有人使用您的搜索,您应该执行以下操作:

  1. Get the search-term via $_POST 通过$ _POST获取搜索字词
  2. Remove all special characters from the search-term ( my'value becomes myvalue ) 从搜索词中删除所有特殊字符( my'value变为myvalue
  3. Replace the search term with MySQL wildcards ( myvalue becomes %m%y%v%a%l%u%e% ) 用MySQL通配符替换搜索词( myvalue变为%m%y%v%a%l%u%e%
  4. Execute SELECT * FROM tab WHERE col LIKE '%m%y%v%a%l%u%e%' 执行SELECT * FROM tab WHERE col LIKE '%m%y%v%a%l%u%e%'

Any of the other solutions will not match all your requirements. 任何其他解决方案都不符合您的所有要求。

SQL Fiddle: http://sqlfiddle.com/#!2/20f811/2 SQL小提琴: http ://sqlfiddle.com/#!2/20f811/2

Use 采用

SELECT * FROM tab WHERE col LIKE '%myvalue%' OR col LIKE '%my_value%'

The underscore _ is a single character wildcard. 下划线_是单个字符通配符。

How about this? 这个怎么样?

SELECT * FROM tab WHERE col LIKE 'my%' OR col LIKE '%value'

this will check col should start with my and end with value. 这将检查col应该从我开始并以值结束。

Demo 演示


Edit 1 编辑1

As there can be any special character and regexp don't work with MySQL, I would suggest you to do what you want to achieve in PHP by replacing special character by null and then matching the string with myvalue. 因为可以有任何特殊字符和regexp不能与MySQL一起工作,我建议你通过将特殊字符替换为null然后将字符串与myvalue匹配来做你想要在PHP中实现的目标。

Hope this helps you. 希望这对你有所帮助。


Edit 2 编辑2

I don't know php exactly, but can tell you what to do little bit. 我完全不知道php,但可以告诉你该做些什么。

mysql = "SELECT id, col FROM tab WHERE col LIKE '%my%' OR col LIKE '%value%'";
rs = mysql.execute();
String newString = "";
while (rs.next()) {
    newString = rs.getString(2);
    newString = new string after replacing special characters using regexp
    if (newString.equals("myvalue")) {
        // your code here..... this is place what you wanted.
    }
} 

Got this... 收到...

PHP Part PHP部分

$term = str_replace('-','',str_replace(',', '', str_replace('\'', '', $term)));

MySql Part MySql部分

SELECT *
FROM tab
WHERE ((REPLACE(REPLACE(REPLACE(col, '\'', ''), ',', ''), '-', '') LIKE "%$term%") 
OR (col LIKE "%$term%"));

See this demo . 看这个演示

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

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