在 MySQL 中使用 LIKE 获取以特定字符开头的名称
mysqlmysqli database
要获取以特定字符开头的名称,您需要使用 LIKE。让我们首先创建一个表:
mysql> create table DemoTable ( StudentFirstName varchar(20) ); Query OK, 0 rows affected (1.01 sec)
下面是使用 insert 命令在表中插入一些记录的查询:
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Johnny'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Ramit'); Query OK, 1 row affected (0.18 sec)
以下是使用 select 命令显示表中记录的查询:
mysql> select *from DemoTable;
这将产生以下输出:
+------------------+ | StudentFirstName | +------------------+ | John | | Carol | | Johnny | | Robert | | Chris | | Ramit | +------------------+ 6 rows in set (0.00 sec)
以下是使用 LIKE 匹配第一个字符的查询:即名字以字符 C 开头的所有学生:
mysql> select *from DemoTable where StudentFirstName LIKE 'C%';
这将产生以下输出:
+------------------+ | StudentFirstName | +------------------+ | Carol | | Chris | +------------------+ 2 rows in set (0.00 sec)