如何从 MySQL 中选择字符串中最后一个值 = x 的记录?

mysqlmysqli database

您可以使用带通配符的 LIKE 运算符来选择字符串中最后一个值 = x 的记录,例如 ‘10’、‘15’ 等。

首先我们创建一个表 −

mysql> create table DemoTable
(
   ClientId varchar(20)
);
Query OK, 0 rows affected (0.68 sec)

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

mysql> insert into DemoTable values('CLI-101');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('CLI-110');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('CLI-201');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('CLI-210');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('CLI-502');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('CLI-1010');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('CLI-1012');
Query OK, 1 row affected (0.15 sec)

以下是使用 select 语句显示表中的所有记录的查询 −

mysql> select *from DemoTable;

这将产生以下输出 −

+----------+
| ClientId |
+----------+
| CLI-101  |
| CLI-110  |
| CLI-201  |
| CLI-210  |
| CLI-502  |
| CLI-1010 |
| CLI-1012 |
+----------+
7 rows in set (0.00 sec)

以下是从 MySQL 中选择字符串中最后一个值 = 10 或 12 的查询。

mysql> select *from DemoTable where ClientId like '%10' or ClientId like '%12';

这将产生以下输出 −

+----------+
| ClientId |
+----------+
| CLI-110  |
| CLI-210  |
| CLI-1010 |
| CLI-1012 |
+----------+
4 rows in set (0.00 sec)

相关文章