我有一个字典表(单词)和另一个表连接2个单词的表,如“helpme”,“helloword”“loveme”......
我想把这张桌子变成“帮助我”,“你好,”,“爱我”
我运行这个序列:
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;
它正在工作,但我的桌子花了很长时间。
如何优化我的sql序列?
----表格的例子--- dictionary_table
|hello|
|word |
|love |
|me |
table_concatened:
的例子|helloword|
|loveyou |
编辑: 1)用例用于自动更正。例如在Skype上,在iPhone上,在Chrome上,当我键入“helloword”时,我会自动更正“hello word”。 2)这里的数据库不是很重要。我们的问题是关于算法逻辑和性能优化。
答案 0 :(得分:0)
如果你不介意去动态(如果是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