0

我想在表中找到包含字符串的行

例如,我在名为“testing”的表中的列名“testing”中有行 -

test
a
cool
another

现在我想使用 sql 从字符串“这是一个测试”中选择具有单词的行

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

但这没有选择任何行。

4

3 回答 3

1

将参数反转为INSTR

WHERE INSTR('this is a test', atext)
于 2013-03-09T19:55:13.270 回答
0

这是一个“颠倒的”,例如:

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

在有很多记录的表上可能会很慢。这将返回行,其中可以在给定字符串中找到 atext 列的值。(例如匹配时 atext = 'is a t' 因为它可以在给定的字符串中找到)

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

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

这匹配所有包含指定单词的行。在您的脚本或编程语言中,您只能将空格替换为 | 并将 ^ 添加到字符串的开头,将 $ 添加到字符串的结尾,以及 REGEXP,而不是等式。(“这是一个测试”-> ^this|is|a|test$ )

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

因此,如果您的表上有很多行并且不超过 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'

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

3 个查询的运行时间之间的结果取决于您的数据库表大小。并且您希望针对插入或选择进行优化。(插入/更新和选择查询之间的速率)

于 2013-03-09T19:54:45.270 回答
0

带全文索引 -

select * from anti_spam where match (atext) against ("this is a test" in boolean mode);
于 2013-03-09T19:59:18.557 回答