MySQL-用来自同一行中另一列的子字符串填充一列 [英] MySQL - populating a column with a substring from another column in the same row

查看:216
本文介绍了MySQL-用来自同一行中另一列的子字符串填充一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to run over an entire table, populating the value of a newly created column with a substring of a value from another column.

给出与以下内容相似的表结构:

Given a table structure not unlike the following:

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

其中包含类似以下数据:

Which contains data resembling:

+----+-------------------------+--------+
| 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   |
+----+-------------------------+--------+

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

I would like to have a query to parse the domain portion of the email address, and put it in the domain column, to end up with a result like:

+----+-------------------------+-------------------+
| 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引擎内部实现更好的方法

Currently, I am doing this outside of the MySQL engine with a shell script, but this is inefficient, and I'm sure there must be a better way to do it inside of the MySQL engine.

效率在这里很重要,因为我将在生产中使用的表是几万甚至数十万行.

Efficiency is important here, as the tables I will be doing this on in production are tens or even hundreds of thousands of rows.

推荐答案

您可以使用或通过此操作更新您的数据:

or this to update your data:

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

请在此处看到小提琴.

这篇关于MySQL-用来自同一行中另一列的子字符串填充一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆