简体   繁体   English

从 SQL 中的字符串中提取前一个单词

[英]extracting previous word from string in SQL

I have an SQL table with employee biographies.我有一张带有员工传记的 SQL 表。

One of the columns is named Biography.其中一列名为传记。

Some entries describe how many years the employee has worked at the company.一些条目描述了员工在公司工作了多少年。

An example:一个例子:

"Gary has worked for us for 8 years" “Gary 为我们工作了 8 年”

I want to extract the number of years each employee has worked for the company.我想提取每个员工为公司工作的年数。

I need an sql query that will identify for each entry the word "years", extract the previous word as an INT, and store this number in the same row as a new column.我需要一个 sql 查询,它将为每个条目识别单词“years”,将前一个单词提取为 INT,并将此数字作为新列存储在同一行中。

Can somebody help explain how to do this for me?有人可以帮我解释一下如何为我做这件事吗?

Thanks.谢谢。

MySQL SUBSTRING_INDEX() returns the substring from the given string before a specified number of occurrences of a delimiter. MySQL SUBSTRING_INDEX()在出现指定数量的分隔符之前从给定字符串返回 substring。

Syntax:句法:

SUBSTRING_INDEX(string, delimeter, count)
  • string: column_name or a constant string字符串:column_name 或常量字符串
  • delimeter: string before which we are finding the prefix分隔符:我们在其前查找前缀的字符串
  • count: The number of times to search for the delimiter count:搜索分隔符的次数

Taking tablename as test and column name which we need to update as new_column and column containing string as query_stringtablename as test ,将需要更新的列名作为new_column ,将包含字符串的列作为query_string

UPDATE test SET new_column=(SELECT SUBSTRING_INDEX(TRIM(SUBSTRING_INDEX(query_string, 'years', 1)), ' ', -1 ) )

Hope this helps!!希望这可以帮助!!

In MySQL, you can use substring_index() :在 MySQL 中,您可以使用substring_index()

select substring_index(trim(substring_index(col, 'years', 1)), ' ', -1) 

Here is a db<>fiddle. 是一个 db<>fiddle。

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

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