【问题标题】:How detect the two word of a string like “helpme”?如何检测像“helpme”这样的字符串的两个单词?
【发布时间】:2017-04-30 10:47:22
【问题描述】:

我有一个字典表(单词)和另一个表,其中连接了 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;

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

如何优化我的 sql 序列?

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

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

table_concatened 示例:

|helloword|
|loveyou |

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

【问题讨论】:

  • 当您知道以后需要再次将它们分开时,为什么还要愚蠢地将它们组合为一个字符串?这总是让我感到惊讶。 我以完全错误的方式存储我的数据,现在我在使用它时遇到了问题。这很复杂/困难/太慢/不能正常工作!有人可以帮忙吗? 答案是肯定的 - 修复您的数据,以便从一开始就正确存储,所有使用它的问题都会消失。当困难的事情一开始并不困难时,您不必优化它们。
  • 您不可能同时使用 SQL Server、PostgreSQL 和 MySQL。为您实际使用的 single DBMS 添加标签,而不是随机添加听起来熟悉的东西。这些数据库之间的语法和功能大不相同,了解您正在使用的特定数据库会对您获得的答案产生影响。请edit您的帖子并删除适用的标签。我知道您在使用 SQL 标记时会收到一个建议,即您应该添加特定的 DBMS 标记,例如 MySQL、SQL Server 等,但这意味着正在使用的特定标记。
  • 您的查询一定会很慢,因为SUBSTRING() 测试无法使用索引进行优化。
  • 注意:我同意你最好正确格式化你的表格,但是......正如你目前的查询,它可以简化为... t2 on t1.word + t2.word = table_concatened.twowords,而不是使用子字符串。此外,substring(x, 1, ...) 在功能上与left(x, ...) 相同,但无论哪种方式,您都无法在此处使用索引。
  • @e4c5:一点也不。谢谢你先问。 :-)

标签: mysql sql sql-server postgresql


【解决方案1】:

如果你不介意动态化(如果是 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 

【讨论】:

  • @nicolasbahout 很高兴为您提供帮助。
猜你喜欢
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
相关资源
最近更新 更多