如何在MySql中从单元格的中间提取单词?

时间:2019-10-04 06:19:13

标签: ssms

我想在另一个新表中提取带有版本的单词,例如:从每个单元格的第二个表中提取“ fruit 2.0”。我怎样才能做到这一点?下面的数据库示例:

select * from mytable where mytab like'%fruit%'.    

 User   MyTab
    1   ["{myfruit":"apple","store":"mystore","username"andy",\\; fruit 2.0 \\,"mysstore is null=false":"133-aascd-ee54-678v"}"]
    2   ["{myfruit":"apple","store":"mystore","username"andy",\\; fruit 1.2 \\,"mysstore is null=false":"133-aascd-ee54-678v"}"]
    3   ["{myfruit":"apple&banana","store":"mystore","username"andy",\\; fruit 3.0 \\,"mysstore is null=false":"133-aascd-ee54-678v"}"]
    4   ["{myfruit":"apple&banana&pineaple","store":"mystore","username"andy",\\;fruit 1.0 \\,"mysstore is null=false":"133-aascd-ee54-678vsadsaafvvrrrv"}"]

我想要的最终结果是:

User    MyTab2
   1    fruit 2.0
   2    fruit 1.2
   3    fruit 3.0
   4    fruit 1.0

某些列属性:

Data Type   varchar
System Type varchar
Length  8000
Collation   SQL_Latin1_General_CP1_CI_AS
Numeric Precision   0
Numeric Scale   0
Is sparse   FALSE
Is Column Set   FALSE
Statistical Semantics   FALSE
Not for Replication FALSE
ANSI Padding Status TRUE
Full Text   FALSE

1 个答案:

答案 0 :(得分:0)

我要在此处发布MSSQL解决方案。这是非常人为设计的(可能效率很低),我觉得您应该从数据库中获取列,然后尝试使用regex提取文本。

    SELECT id, SUBSTRING(
      mytab, 
      PATINDEX('%fruit [0-9\.]%', mytab), 
      PATINDEX('%\\,%', mytab)-PATINDEX('%fruit [0-9\.]%', mytab) FROM mytable;

基本上,我在这里是

  • 使用PATINDEX找到X = All 'fruit' occurences followed by a floating number (version)
  • Y = \\,的位置,该位置紧随您共享的数据样本中的字符串之后的顺序
  • 我使用MSSQL的SUBSTRING函数从该位置提取子字符串  SUBSTRING(mytab, X, Y-X)

Working SQL Fiddle