mysql - 如何检测像 “helpme” 这样的字符串的两个单词?

标签 mysql sql sql-server postgresql

我有一个字典表(单词)和另一个包含 2 个单词的连接表,例如“helpme”、“helloword”、“loveme”...

我想把这张表改成“help me”、“hello word”、“love me”

我运行这个序列:

SELECT 
  table_concatened.twowords,
  t1.word as 'word1',
  t2.word as 'word2'
FROM
 table_concatened
  JOIN dictionary_table AS t1 ON SUBSTRING(table_concatened.twowords,1,len(t1.word)) = t1.word 
  JOIN dictionary_table AS t2 ON SUBSTRING(table_concatened.twowords,len(t1.word)+1,len(table_concatened.twowords)) = t2.word;

它正在工作,但我的 table 花了很长时间。

如何优化我的 sql 序列?

---- 表格示例 --- 字典表

 |hello|
 |word |
 |love |
 |me   |

table_concatened 的例子:

|helloword|
|loveyou |

编辑: 1)用例用于自动更正。例如,在 Skype、iPhone、Chrome 上,当我输入“helloword”时,我会自动更正为“hello word”。 2)这里的数据库不是很重要。我们的问题是关于算法逻辑和性能优化。

最佳答案

如果你不介意动态化(如果是 SQL Server)

-- Generate Some Sample Data
Declare @Dictionary_Table table (word varchar(50));Insert Into @Dictionary_Table values ('hello'),('word'),('love'),('me')
Declare @table_concatened table (ID int,twowords varchar(50));Insert Into @table_concatened values (1,'helloword'),(2,'loveyou')

-- Generate SQL and Execute
Declare @SQL varchar(max)=''
Select  @SQL = @SQL+concat(',(',ID,',''||',replace(twowords,'''',''''''),'||'')') From @table_concatened --Where ID=2
Select  @SQL = Replace(@SQL,MapFrom,MapTo) 
 From   (
         Select MapFrom = word
               ,MapTo   = '|'+ltrim(rtrim(word))+'|'
          From  @Dictionary_Table
          Union All
          Select '|',' '   -- Remove Any Remaining |
          Union All
          Select '  ',' '     -- Remove Any Remaining |
         ) A
Select  @SQL = 'Select ID,Value=ltrim(rtrim(Value)) From ('+Stuff(@SQL,1,1,'values')+') N(ID,Value)'
Exec(@SQL)

返回

ID    Value
1     hello word  
2     love you 

关于mysql - 如何检测像 “helpme” 这样的字符串的两个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41153889/

相关文章:

php - Android - 通过 PHP 通过 HTTPClient 连接 MySQL

sql - 地址中包含逗号的 CSV 文件

python - 在Python中使用sql将一行合并在一列中

sql-server - SSMS对象浏览器排序顺序?

sql - TSQL 模式(如平均值、中位数、众数)

sql-server - 通过将参数作为查询传递来执行sql存储过程

php - 如何使用 mysql 从多个类别中选择行并显示每个类别的数据列表?

php - SQL查询将两列与另一表中的一列进行比较(并获取两个值)

php - 比较两个不同类型的数据库表并比较它们的数据的最佳方法?

sql - 指定外键是否会自动处理外表值的更新?