MySQL
 Computer >> コンピューター >  >> プログラミング >> MySQL

MySQLデータベースで特定の文字列のみの文字列を見つけて置き換える方法は?


replace()関数を使用して、MySQLデータベースの文字列を置き換えます。

構文は次のとおりです

UPDATE yourTableName
SET yourColumnName=replace(yourColumnName,'yourExistingValue','yourNewValue')
WHERE <yourCondition>>;

上記の構文を理解するために、テーブルを作成しましょう。テーブルを作成するためのクエリは次のとおりです

mysql> create table findAndReplaceDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentFirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.49 sec)

挿入コマンドを使用して、テーブルにいくつかのレコードを挿入します。

クエリは次のとおりです

mysql> insert into findAndReplaceDemo(StudentFirstName) values('Carol');
Query OK, 1 row affected (0.15 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Bob');
Query OK, 1 row affected (0.10 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Maxwell');
Query OK, 1 row affected (0.17 sec)

selectステートメントを使用してテーブルのすべてのレコードを表示します。

クエリは次のとおりです

mysql> select *from findAndReplaceDemo;

以下は出力です

+----+------------------+
| Id | StudentFirstName |
+----+------------------+
| 1  | Carol            |
| 2  | David            |
| 3  | Bob              |
| 4  | Sam              |
| 5  | Mike             |
| 6  | Maxwell          |
+----+------------------+
6 rows in set (0.00 sec)

これは、MySQLデータベースで特定の文字列のみの文字列を検索して置換するためのクエリです

mysql> update findAndReplaceDemo
   -> set StudentFirstName=replace(StudentFirstName,'Maxwell','Chris')
   -> where StudentFirstName='Maxwell';
Query OK, 1 row affected (0.16 sec)
Rows matched: 1 Changed: 1 Warnings: 0

テーブルレコードをもう一度確認してみましょう。値「Maxwell」が「Chris」に変更されました。

クエリは次のとおりです

mysql> select *from findAndReplaceDemo;

以下は、値が更新された出力です

+----+------------------+
| Id | StudentFirstName |
+----+------------------+
| 1  | Carol            |
| 2  | David            |
| 3  | Bob              |
| 4  | Sam              |
| 5  | Mike             |
| 6  | Chris            |
+----+------------------+
6 rows in set (0.00 sec)

  1. MySQL:特殊文字を含む値を見つけてNULLに置き換えるにはどうすればよいですか?

    これには、次の構文のようにSET yourColumnName=NULLを使用します- update yourTableName set yourColumnName=NULL where yourColumnName=yourValue; まずテーブルを作成しましょう- mysql> create table DemoTable1914    (    Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,    Code varchar(20)    )AUTO_INCR

  2. MySQLで文字列の最初に繰り返される値のみを置き換える方法

    これには、REGEXP_REPLACE()を使用できます。文字列が-だとしましょう This is my first MySQL query. This is the first tutorial. I am learning for the first time. 特定の単語の最初の出現のみを置き換える必要があります。たとえば、「最初」としましょう。出力は-である必要があります This is my second MySQL query. This is the first tutorial. I am learning for the first time. テーブルを作成しましょう-