MySQL 查询检查字符串是否在同一行中包含值(子字符串)?

mysqlmysqli database

由于我们需要匹配同一行中的字符串,因此使用 LIKE 运算符。让我们首先创建一个表 −

mysql> create table DemoTable
(
   FirstName varchar(100),
   FullName varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

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

mysql> insert into DemoTable values('John','John Smith');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('David','John Miller');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob','Sam Miller');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Chris','Chris Brown');
Query OK, 1 row affected (0.10 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 −

+-----------+-------------+
| FirstName | FullName    |
+-----------+-------------+
| John      | John Smith  |
| David     | John Miller |
| Bob       | Sam Miller  |
| Chris     | Chris Brown |
+-----------+-------------+
4 rows in set (0.00 sec)

以下查询用于检查字符串是否在同一行中包含值 −

mysql> select FirstName,FullName from DemoTable
   where FullName LIKE concat('%', FirstName, '%');

这将产生以下输出 −

+-----------+-------------+
| FirstName | FullName    |
+-----------+-------------+
| John      | John Smith  |
| Chris     | Chris Brown |
+-----------+-------------+
2 rows in set (0.00 sec)

相关文章