【问题标题】:MySQL - populating a column with a substring from another column in the same rowMySQL - 用同一行中另一列的子字符串填充一列
【发布时间】:2014-11-27 15:37:45
【问题描述】:

我想遍历整个表,用另一个列的值的子字符串填充新创建列的值。

给定一个类似于以下的表结构:

+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| email  | varchar(150) | YES  |     | NULL    |                |
| domain | varchar(100) | YES  |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+

其中包含类似的数据:

+----+-------------------------+--------+
| id | email                   | domain |
+----+-------------------------+--------+
|  1 | bob@domain1.com         | NULL   |
|  2 | jim@domain1.com         | NULL   |
|  3 | terry@domain1.com       | NULL   |
|  4 | frank@anotherdomain.com | NULL   |
|  5 | linda@anotherdomain.com | NULL   |
|  6 | craig@thethird.com      | NULL   |
+----+-------------------------+--------+

我想要一个查询来解析电子邮件地址的域部分,并将其放在域列中,最终得到如下结果:

+----+-------------------------+-------------------+
| id | email                   | domain            |
+----+-------------------------+-------------------+
|  1 | bob@domain1.com         | domain1.com       |
|  2 | jim@domain1.com         | domain1.com       |
|  3 | terry@domain1.com       | domain1.com       |
|  4 | frank@anotherdomain.com | anotherdomain.com |
|  5 | linda@anotherdomain.com | anotherdomain.com |
|  6 | craig@thethird.com      | thethird.com      |
+----+-------------------------+-------------------+

目前,我正在使用 shell 脚本在 MySQL 引擎的外部执行此操作,但这效率低下,我确信在 MySQL 引擎内部必须有更好的方法来执行此操作.

效率在这里很重要,因为我将在生产中执行此操作的表有数万甚至数十万行。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    你可以使用SUBSTRING_INDEX:

    SELECT
      id,
      email,
      SUBSTRING_INDEX(email, '@', -1) domain
    FROM
      yourtable
    

    或者这个来更新你的数据:

    UPDATE yourtable
    SET domain = SUBSTRING_INDEX(email, '@', -1)
    

    请看小提琴here

    【讨论】:

    • 您没有像所有其他答案一样更新表格。
    【解决方案2】:
    update your_table
    set domain = SUBSTRING_INDEX(email, '@', -1)
    where domain is null;
    

    如果表很大,您应该考虑将更新分成块。我建议使用 common_schema 中的split 函数来做到这一点。

    【讨论】:

      【解决方案3】:

      使用SUBSTRING_INDEX:

      如果 count 为负数,则最后定界符右侧的所有内容 (从右数)返回。

      所以要让@右侧的所有内容,您可以提供一个负数:

      UPDATE YourTable
      SET Domain = SUBSTRING_INDEX(email, '@', -1)
      

      SQL Fiddle

      【讨论】:

        【解决方案4】:
        -1 will give the value after `@`
        
        update tablename set domain = SUBSTRING_INDEX(email, '@', -1)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-24
          • 1970-01-01
          • 2022-11-24
          • 2015-03-19
          相关资源
          最近更新 更多