如何在数据库中搜索子字符串?

时间:2014-06-07 13:04:18

标签: mysql sql

我的数据库表中有两列:

-------------------------------
name            | address
-------------------------------
raj kumar       | park street    
yogin patel     | ghari chowk 
raju singh      | sultan ganj

我想检索包含sultan ganj的行,但是我错误地搜索sultanganj单词之间没有空格)。我将使用什么查询来获得正确的结果?

4 个答案:

答案 0 :(得分:1)

您可以REPLACE字段address中包含空字符串的所有空格,并将其与sultanganj进行比较:

SELECT * 
FROM `table`
WHERE REPLACE(`address`, ' ', '') = 'sultanganj'

这会让你回复:

-------------------------
    name   |   address
-------------------------
raju singh | sultan ganj

答案 1 :(得分:1)

使用REPLACE函数替换下面的额外空格

select name, address
from yourtable
where replace(address,' ','') = 'sultanganj'

修改

您可以在回答中使用相同的查询,但将WHERE条件更改为类似于'%park%'或者说道路是'%road%'。这样,它将匹配包含单词parkroadboth的所有地址(例如:parkroadparkstreetHellRoadHeavenpark等。)

select name, address
from yourtable
where address like '%park%' or address like '%road%'

答案 2 :(得分:0)

以下查询将为您提供帮助

select * from table1 Where replace(address,' ','') = replace('sultanganj',' ','')

答案 3 :(得分:0)

SELECT * FROM table where replace(`address`,' ', '' ) like '%your search element%' or `address` like '%your search element%'

此查询为我工作

修改

(1)SELECT * FROM table where replace(`address`,' ', '' ) like '%parkstreet%' or `address` like '%parkstreet%'
(2)SELECT * FROM table where replace(`address`,' ', '' ) like '%park%' or `address` like '%park%'
(3)SELECT * FROM table where replace(`address`,' ', '' ) like '%street%' or `address` like '%street%'
(4)SELECT * FROM table where replace(`address`,' ', '' ) like '%park street%' or `address` like '%park street%'