简体   繁体   English

如何替换MYSQL中列的某个值?

[英]how to replace a certain value of a column in MYSQL?

how to replace a certain value of a column. 如何替换列的某个值。 for example I have three rows of values ​​in a table: 例如我在一个表中有三行值:

id_tweet: 1
status_user: RT @username1: success rta: P

id_tweet: 2
status_user: RT @username2: happy rta: D

id_tweet: 3
status_user: amen

of the three records above I want to replace or remove retweet text in the status_user column to: 我想将status_user列中的转发文本替换或删除为上述三个记录中的一个,以:

after replace:

id_tweet: 1
status_user: success rta: P

id_tweet: 2
status_user: happy rtx: D

id_tweet: 3
status_user: amen

but I have constraints. 但我有限制。 I think I can use the replace function query on mysql as follows: 我想我可以在MySQL上使用替换函数查询,如下所示:

UPDATE tes_tbl_status
SET status_user = (SELECT REPLACE (status_user, '?', '') FROM 
tes_tbl_status WHERE status_user LIKE 'RT%:%')
WHERE status_user LIKE 'RT%:%';

information : '?' 信息:“?” = RT @...: = RT @ ...:

query above by replacing a certain value in the status_user column with an empty string value, however I do not yet know how to retrieve the text value 通过将status_user列中的某个值替换为空字符串值来进行上述查询,但是我尚不知道如何检索文本值

RT @ ...: RT @ ...:

which will be replaced with an empty string. 它将被替换为空字符串。 anyone have any idea or solution for my problem? 有人对我的问题有任何想法或解决方案吗?

If you want to remove always the RT @...: parts, the SUBSTRING_INDEX , CONCAT and REPLACE mysql functions are there for your help. 如果要始终删除RT @...:部件,则可以使用SUBSTRING_INDEXCONCATREPLACE mysql函数。 Using SUBSTRING_INDEX you can extract the RT @... substring that you can CONCAT with a colon ( : ) and apply this result in the REPLACE function as the from_str parameter to be replaced by an empty string. 使用SUBSTRING_INDEX您可以提取RT @...子,你可以用冒号CONCAT( : :和在应用此结果REPLACE函数作为from_str参数由一个空字符串代替。

Here is the code what do the update for you: 以下是代码为您执行的更新:

UPDATE t
SET status_user = TRIM(REPLACE(status_user, CONCAT(SUBSTRING_INDEX(status_user, ':', 1),':'), ''))
WHERE status_user LIKE 'RT%';

Result : 结果

+----------+----------------+
| id_tweet | status_user    |
+----------+----------------+
|        1 | success rta: P |
|        2 | happy rta: D   |
|        3 | amen           |
+----------+----------------+

Note the TRIM that i used to remove the leading and trailing spaces (if exist). 注意我用来删除前导和尾随空格(如果存在)的TRIM

See sqlfiddle demo here . 在此处查看sqlfiddle演示

DDL : DDL

CREATE TABLE t (
  id_tweet INT UNSIGNED NOT NULL,
  status_user TEXT NOT NULL
);

INSERT INTO t (id_tweet, status_user) VALUES
(1, 'RT @username1: success rta: P'),
(2, 'RT @username2: happy rta: D'),
(3, 'amen');

Also there is a nice mysql udf library ( lib_mysqludf_preg ) that can equips your mysql with PCRE pattern matching functionalities. 另外,还有一个不错的mysql udf库( lib_mysqludf_preg ),可以为您的mysql配备PCRE模式匹配功能。

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

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