如何在 MySQL 中匹配一个字符来代替 %?
mysqlmysqli database
要在 MySQL 中仅匹配一个字符,可以使用下划线 (_) 代替 %。语法如下:
SELECT *FROM yourTableName WHERE yourColumnName LIKE ‘yourString_’;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table OneCharactermatchDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> PassoutYear year, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.76 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下:
mysql> insert into OneCharactermatchDemo(PassoutYear) values('2008'); Query OK, 1 row affected (0.14 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2007'); Query OK, 1 row affected (0.18 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2010'); Query OK, 1 row affected (0.10 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2011'); Query OK, 1 row affected (0.13 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2012'); Query OK, 1 row affected (0.12 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2006'); Query OK, 1 row affected (0.10 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2019'); Query OK, 1 row affected (0.14 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2016'); Query OK, 1 row affected (0.13 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2017'); Query OK, 1 row affected (0.34 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2015'); Query OK, 1 row affected (0.17 sec) mysql> insert into OneCharactermatchDemo(PassoutYear) values('2020'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录。查询如下:
mysql> select *from OneCharactermatchDemo;
输出结果如下:
+----+-------------+ | Id | PassoutYear | +----+-------------+ | 1 | 2008 | | 2 | 2007 | | 3 | 2010 | | 4 | 2011 | | 5 | 2012 | | 6 | 2006 | | 7 | 2019 | | 8 | 2016 | | 9 | 2017 | | 10 | 2015 | | 11 | 2020 | +----+-------------+ 11 rows in set (0.00 sec)
以下是使用下划线匹配一个字符的查询。查询如下:
mysql> select *from OneCharactermatchDemo where PassoutYear Like '200_';
输出结果如下:
+----+-------------+ | Id | PassoutYear | +----+-------------+ | 1 | 2008 | | 2 | 2007 | | 6 | 2006 | +----+-------------+ 3 rows in set (0.00 sec)