找到文本位置,提取文本并插入MySQL中的新列

时间:2014-10-17 23:48:07

标签: mysql string return-value extract

我在MySQl表中有以下行示例

              Column A    

Row1    Lauguage=English&Country=USA&Gender=Male
Row2    Gender=Female&Language=French&Country=
Row3    Country=Canada&Gender=&Language=English

如何实现以下目标:例如,我需要查找国家/地区

  1. 我需要在此文本列中找到Country的位置。这会逐行变化。
  2. 我需要忽略参数' Country ='并且只提取值。在某些情况下,这将是NULL(如Row2中的示例),而在某些行中,我需要值后跟' =' (例如Row1& Row3中的示例)。但是,我需要确保我只获得价值。不是由'&'
  3. 分隔的下一个参数
  4. 提取Country参数的值后,我需要创建一个新列,现在将提取并存储这些值。
  5. 结束结果:新列

                  Column B                                                
    
    Row1            USA                            
    Row2                              
    Row3           Canada                                  
    

    任何帮助都将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:7)

您可以选择'Country ='后的文字,然后一旦有了子字符串,请在第一个'&'之前选择文字

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1) AS ColumnB
FROM `atable`

请参阅http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_substring-index


这是一个测试来证明:

mysql> SELECT * FROM atable;
+------+------------------------------------------+
| row  | columna                                  |
+------+------------------------------------------+
| Row1 | Lauguage=English&Country=USA&Gender=Male |
| Row2 | Gender=Female&Language=French&Country=   |
| Row3 | Country=Canada&Gender=&Language=English  |
+------+------------------------------------------+

mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1) AS ColumnB FROM atable;
+---------+
| ColumnB |
+---------+
| USA     |
|         |
| Canada  |
+---------+

重新提出你的后续问题:

INSERT INTO atable VALUES ('Row4', 'Gender=&Language=English');

SELECT `row`, IF(LOCATE('Country=', ColumnA)>0, 
  COALESCE(
    NULLIF(SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1), ''), 
    'Blank string is not valid!'), 
 'Missing Country!') AS ColumnB     
FROM `atable`

+------+----------------------------+
| row  | ColumnB                    |
+------+----------------------------+
| Row1 | USA                        |
| Row2 | Blank string is not valid! |
| Row3 | Canada                     |
| Row4 | Missing Country!           |
+------+----------------------------+

答案 1 :(得分:0)

但是我有完全相同的问题,在SQL中,对于任何想要SQL答案的人,请参见Tim Biegeleisen评论here

create table elb_logs(row varchar(100), url varchar(100));
insert into elb_logs values("Row1", "Lauguage=English&Country=USA&Gender=Male");

SELECT
    row,
    CASE WHEN POSITION('Country=' IN url) > 0
         THEN SPLIT_PART(SPLIT_PART(url, 'Country=', 2), '&', 1)
         ELSE 'Missing Country!' END AS ColumnB
FROM elb_logs;