简体   繁体   English

从SQL表的列中检索特定的字符串

[英]Retrieve specific string from column in SQL table

Hi I have the following data column where the typical data will look like: 嗨,我有以下数据列,典型数据如下所示:

Row 1: RCS CARD: THANK YOU FOR YOUR PURCHASE AT PICK N PAY ON CARD ...1820 FOR R371.71 ON 14-03-2013 AT 09:46. 第1行:RCS卡:谢谢您在卡上选择N Pay付款... 1820于2013年3月14日在09:46 R371.71。 AVAIL CREDIT R67. 可用信用R67。 FOR QUERIES CALL 0861028889 查询电话0861028889

Row 2: RCS CARD: THANK YOU FOR YOUR PURCHASE AT PICK N PAY ON CARD ...6825 FOR R3061.93 ON 14-03-2013 AT 09:45. 第2列:RCS卡:谢谢您在卡上选择N Pay付款... 6825 for R3061.93 on 14-03-2013 at 09:45。 AVAIL CREDIT R39. 可用信用R39。 FOR QUERIES CALL 0861028889 查询电话0861028889

I need to be able to extract the R371.71 and R3061.93 from row 1 and 2. What is the most accurate way to do this? 我需要能够从第1行和第2行中提取R371.71和R3061.93。最准确的方法是什么? Keeping in mind that R amount will change from row to row so a simple substring will not work? 请记住,R的数量会在行与行之间变化,所以简单的子字符串不起作用?

Any advice would be extremely helpful. 任何建议都将非常有帮助。

Thanks, Jonathan 谢谢乔纳森

Well the proper way to do it is to use regexp in an external script/app since MySQL doesn't support regular expression sub strings. 正确的方法是在外部脚本/应用程序中使用regexp,因为MySQL不支持正则表达式子字符串。

If you do insist on using SQL the only way I could think of is by assuming that the string starts with: 如果您确实坚持使用SQL,那么我能想到的唯一方法就是假设字符串以:

RCS CARD: THANK YOU FOR YOUR PURCHASE AT PICK N PAY ON CARD RCS卡:谢谢您通过PICK N PAY购买

and just ignore that part. 而忽略那部分。 so the SQL should be: 因此,SQL应该是:

SELECT SUBSTR(t, LOCATE('FOR', t, 61)+5 ,LOCATE('ON', t, 61)-1-LOCATE('FOR', t, 61)-5)
  FROM DATA

Again I would use regexp but you can see it's working in this SQLFiddle: http://sqlfiddle.com/#!2/966ad/7 同样,我将使用regexp,但是您可以看到它在此SQLFiddle中正在工作: http ://sqlfiddle.com/#!2/966ad/7

If the column in concern has consistent text format as you mentioned in the question, then you can make use of substring_index , locate and substring functions to find the amount value. 如果所关注的column具有您在问题中提到的一致的文本格式,则可以使用substring_indexlocatesubstring函数来查找金额值。

select  
  -- column_name,  
  substring_index( substring( column_name,   
                              locate( 'FOR R', column_name, 1 ) 
                               + length( 'FOR R' ) 
                               - 1 
                   ), ' ', 1   
  ) as amount  
from table_name  
where   
  column_name like '%RCS CARD: THANK YOU FOR YOUR PURCHASE AT PICK N PAY ON CARD%';

Demo @ MySQL 5.5.32 Fiddle 演示 @ MySQL 5.5.32 Fiddle

If you want to extract only the amount without prefix 'R' then, remove the '-1' line from the above query. 如果您只想提取不带前缀'R'的金额,则从上面的查询中删除'-1'行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM