我有一个包含文本字符串的列,我想获取包含给定句子中的单词的所有行,例如:
如果给出句子:
在田野中间的桌子上的红苹果
和列包含以下行:
- 红色
- 该领域的红苹果
- 绿色苹果
- 红色苹果在椅子上
- 表
醇>
我希望我的查询只返回第1,2和5行。
答案 0 :(得分:1)
这应该这样做:
SELECT [RowNumber] FROM [Table] WHERE INSTR('the red apple on the table in the middle of the field', [ColumnText]) <> 0
显然,您需要更改方括号中的位以匹配您的数据库。
编辑 - 是的,我的错 - 我从来没有完全读过你的问题,意识到你也想找到这些单词按照正确的顺序匹配但整个短语不匹配的情况。我可以在TSQL中这样做:
DECLARE @Sentence VARCHAR(100) = 'the red apple on the table in the middle of the field';
DECLARE @Column VARCHAR(100) = 'the red';
SELECT @Column, '%' + REPLACE(@Column, ' ', '%') + '%', CASE WHEN @Sentence LIKE '%' + REPLACE(@Column, ' ', '%') + '%' THEN 1 ELSE 0 END;
SELECT @Column = 'red apple of the field';
SELECT @Column, '%' + REPLACE(@Column, ' ', '%') + '%', CASE WHEN @Sentence LIKE '%' + REPLACE(@Column, ' ', '%') + '%' THEN 1 ELSE 0 END;
SELECT @Column = 'green apple';
SELECT @Column, '%' + REPLACE(@Column, ' ', '%') + '%', CASE WHEN @Sentence LIKE '%' + REPLACE(@Column, ' ', '%') + '%' THEN 1 ELSE 0 END;
SELECT @Column = 'red apple on the chair';
SELECT @Column, '%' + REPLACE(@Column, ' ', '%') + '%', CASE WHEN @Sentence LIKE '%' + REPLACE(@Column, ' ', '%') + '%' THEN 1 ELSE 0 END;
SELECT @Column = 'table';
SELECT @Column, '%' + REPLACE(@Column, ' ', '%') + '%', CASE WHEN @Sentence LIKE '%' + REPLACE(@Column, ' ', '%') + '%' THEN 1 ELSE 0 END;
SELECT @Column = 'field of red apple';
SELECT @Column, '%' + REPLACE(@Column, ' ', '%') + '%', CASE WHEN @Sentence LIKE '%' + REPLACE(@Column, ' ', '%') + '%' THEN 1 ELSE 0 END;
这也适用于SQLite,例如:
SELECT [RowNumber] FROM [Table] WHERE 'the red apple on the table in the middle of the field' LIKE '%' + REPLACE([ColumnText], ' ', '%') + '%'
答案 1 :(得分:1)
基本上你需要根据空格分割行文本。现在检查每个slpit字符串的“Like%+ splitString [i] +%”,然后对其应用AND操作。
答案 2 :(得分:0)
对于上面的例子,这个查询对我有用:
SELECT * FROM [table] WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([column],'the',''),'red',''),'apple',''),'on',''),'the',''),'table',''),'in',''),'the',''),'middle',''),'of',''),'the',''),'field',''),' ','') = ''
这是为输入字符串自动生成SQL查询的java代码&#34; speechString&#34;:
String[] words = speechString.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll("[^\\w]", "");
}
String replaceStr = "REPLACE("+[column]+",'"+words[0]+"','')";
for (int i = 1; i < words.length; i++) {
replaceStr = "REPLACE("+replaceStr+",'"+words[i]+"','')";
}
replaceStr = "REPLACE("+replaceStr+",' ','')";
String query = "SELECT * FROM "+[table]+" WHERE "+replaceStr+" = ''";
替换上面代码中的[column]和[table]。