我有一个字典表(单词)和另一个包含 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/