MySQL 查询使用 LIKE 来选择行并创建包含匹配字符串的新列?

mysqlmysqli database更新于 2024/1/9 17:06:00

为此,请使用 SUBSTRING()。让我们首先创建一个表 −

mysql> create table DemoTable1872
   (
   Name varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable1872 values('John Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1872 values('Adam Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1872 values('Mitchell Johnson');
Query OK, 1 row affected (0.00 sec)

使用 select 语句显示表中的所有记录 −

mysql> select * from DemoTable1872;

这将产生以下输出 −

+------------------+
| Name             |
+------------------+
| John Doe         |
| Adam Smith       |
| Mitchell Johnson |
+------------------+
3 rows in set (0.00 sec)

以下查询用于选择具有 LIKE 的行并创建包含匹配字符串的新列 −

mysql> select Name,
   substring(Name, locate('John', Name), length('John')) as NewName
   from DemoTable1872
   where Name like '%John%';

这将产生以下输出 −

+------------------+---------+
| Name             | NewName |
+------------------+---------+
| John Doe         | John    |
| Mitchell Johnson | John    |
+------------------+---------+
2 rows in set (0.00 sec)

相关文章