MySQL查询以检查字符串是否在同一行中包含值(子字符串)?
由于我们需要匹配同一行中的字符串,因此请使用LIKE运算符。让我们首先创建一个表-
mysql> create table DemoTable ( FirstName varchar(100), FullName varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('John','John Smith'); mysql> insert into DemoTable values('David','John Miller'); mysql> insert into DemoTable values('Bob','Sam Miller'); mysql> insert into DemoTable values('Chris','Chris Brown');
使用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)