2013-03-09 83 views
0

我想找到其中包含字符串SQL查找行部分匹配的字符串

例如,具有表行的行,我在一个名为“测试”表中的列名“ATEST” M具有行 -

test 
a 
cool 
another 

现在我要选择具有从字符串“这是测试”使用SQL

select * from testing where instr(atext, 'this is a test') >0; 

但这不选择任何行字行。

回答

1

将参数取反到INSTR

WHERE INSTR('this is a test', atext) 
+0

INSTR是MySQL的的反转方式,搞笑为什么会这样? – 2013-03-11 16:20:14

+0

@PradyutBhattacharya我从来没有在另一种编程语言中看过INSTR。我能想到的唯一模拟是PHP'strpos',它具有与MySQL相同的参数顺序。 – 2013-03-11 16:27:34

+0

instr非常有名,在javascript,vb中,每隔一种类型的旧lang ... – 2013-03-11 17:37:54

0

这是一个“颠倒”,如:

select * from testing where 'this is a test' LIKE CONCAT('%',atext,'%'); 

它可以在具有大量记录的表慢。 这将返回行,其中可以在给定字符串中找到atext列的值。 (例如,当atext ='是t时匹配,因为它可以在给定的字符串中找到)

或者你可以写一个正则表达式。

select * from testing where atext REGEXP '^(this|is|a|test)$'; 

这匹配所有行包含完全指定的单词。 在你的脚本或编程语言中,你应该只用|并将^添加到字符串的开头,将$添加到字符串的结尾,REGEXP不是等式。 (“This is a test” - >^this | is | a | test $)

如果表中有很多记录,则此查询可能会很慢。因为sql引擎不在正则表达式查询中使用索引。

所以,如果你的桌子上有很多行,没有超过4 000 000字,我建议做一个索引表。例如:

originalTable: 
tid | atext (text)   
1 | this is   
2 | a word   
3 | a this 
4 | this word  
5 | a is 
.... 



indexTable: 
wid | word (varchar) 
1 | this 
2 | is 
3 | a 
4 | word 


switchTable: 
tid | wid 
1 | 1 
1 | 2 
2 | 3 
2 | 4 
3 | 1 
3 | 3 
... 

您应该设置索引,tid,wid和word字段。

比查询是:

SELECT o.* 
FROM originalTable as o 
JOIN switchTable as s ON o.tid = s.tid 
JOIN indexTable as i on i.wid=s.wid 
WHERE i.word = 'this' or i.word='is' or i.word='a' or i.word='test' 

此查询可以是mutch更快,如果你有originalTable“很多”的记录,因为这里的SQL引擎可以使索引搜索。但是,在原始表格中插入一行时,您还需要做更多的工作,您必须在其他两个表格中进行插入。

3个查询的运行时间之间的结果取决于您的数据库表大小。而且你想优化插入或选择。 (插入/更新和选择查询之间的比率)

0

全文索引 - 在编程语言

select * from anti_spam where match (atext) against ("this is a test" in boolean mode);