使用 LIKE 子句两次显示表中重复的 FirstName 和 LastName 的特定名称

mysqlmysqli database更新于 2024/4/7 13:12:00

首先我们创建一个表 −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(30)
);
Query OK, 0 rows affected (0.70 sec)

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

mysql> insert into DemoTable(StudentName) values('John Smith');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('David Miller');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('Carol Taylor');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('John Doe');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Chris Brown');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentName) values('Adam Doe');
Query OK, 1 row affected (0.11 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 −

+-----------+---------------+
| StudentId | StudentName   |
+-----------+---------------+
|         1 | John Smith    |
|         2 | David Miller  |
|         3 | Carol Taylor  |
|         4 | John Doe      |
|         5 | Chris Brown   |
|         6 | Adam Doe      |
+-----------+---------------+
6 rows in set (0.00 sec)

以下查询从表中选择名字为"John"且姓氏为"Doe"的记录 −

mysql> select *from DemoTable
   where StudentName LIKE '%John%' and StudentName LIKE '%Doe%';

这将产生以下输出 −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         4 | John Doe    |
+-----------+-------------+
1 row in set (0.00 sec)

相关文章