当使用SQL(Teradata)模糊搜索多个单词时,在结果中,如何列出匹配的单词?

时间:2018-04-20 20:14:39

标签: sql database teradata tabular fuzzy-search

我想用来查询一些记录,如:

select table1.survey_txt where table1.survey_txt like any (
'%aaaa%',
'%bbbb%',
'%cccc%',
'%dddd%',
'%eeee%',
'%[^a-z0-9]ffff[^a-z0-9]%'
)

结果如下:

survey_txt

heheaaaahehe

kekeaaaakeke

uueabbbbk

jioewccccfjo

esjoffffownr

那么如何才能得到如下结果:

survey_txt .......... matched_word

heheaaaahehe ........ AAAA

kekeaaaakeke ......... aaaa

uueabbbbk ............... BBBB

jioewccccfjo .............. CCCC

esjoffffownr .................. FFFF

这是一张桌子,但我不知道如何在这里制作一张桌子所以我只是用“.....”使它看起来像桌子。

2 个答案:

答案 0 :(得分:3)

Use REGEXP_SUBSTR instead of LIKE:

SELECT survey_txt,
   RegExp_Substr(survey_txt, '(aaaa|bbbb|cccc|dddd|eeee|[^a-z0-9]ffff[^a-z0-9])') AS matched_word
FROM surveys
WHERE matched_word IS NOT NULL

答案 1 :(得分:0)

尝试使用搜索词和类似字符串构建表,然后进行内部连接。由于你使用的是Teradata,这样的例子应该可行:

CREATE VOLATILE TABLE searchwordslist
  (searchword VARCHAR(32)
  , likestring VARCHAR(32))
ON COMMIT PRESERVE ROWS
;
INSERT INTO searchwordslist VALUES('aaaa', '%aaaa%');
INSERT INTO searchwordslist VALUES('bbbb', '%bbbb%'); 
--and so on for all the words

现在我们的searchwordlist表格如下:

searchword  likestring
bbbb        %bbbb%
aaaa        %aaaa%

然后你的查询是:

SELECT a.survey_txt 
  , b.searchword
FROM table1 a
INNER JOIN searchwordslist b
  ON a.survey_txt LIKE b.likestring
;

给出您想要的结果:

survey_txt      searchword
heheaaaahehehe  aaaa
kekebbbbkeke    bbbb