对 INT 字段执行 MySQL LIKE 比较?

mysqlmysqli database

您需要使用 cast() 方法对 INT 字段进行比较。语法如下 −

SELECT yourColumnName1,yourColumnName2,......N yourTableName WHERE CAST(yourColumnName as CHAR) LIKE ‘%yourIntegerValue%’;

为了理解上述语法,让我们创建一个表。以下是创建用于对 INT 字段执行 LIKE 比较的表的查询 −

mysql> create table ComparisonOnIntField
   -> (
   -> StudentId int NOT NULL,
   -> StudentName varchar(20),
   -> StudentAge int
   -> );
Query OK, 0 rows affected (1.00 sec)

在表中插入一些记录,对 INT 字段执行 MySQL LIKE 比较。插入记录的查询如下 −

mysql> insert into ComparisonOnIntField values(10,'Carol',24);
Query OK, 1 row affected (0.17 sec)

mysql> insert into ComparisonOnIntField values(12,'Bob',21);
Query OK, 1 row affected (0.18 sec)

mysql> insert into ComparisonOnIntField values(14,'Sam',23);
Query OK, 1 row affected (0.10 sec)

mysql> insert into ComparisonOnIntField values(16,'Mike',25);
Query OK, 1 row affected (0.26 sec)

mysql> insert into ComparisonOnIntField values(18,'John',27);
Query OK, 1 row affected (0.14 sec)

mysql> insert into ComparisonOnIntField values(20,'David',26);
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from ComparisonOnIntField;

以下是输出。

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|        10 | Carol       |         24 |
|        12 | Bob         |         21 |
|        14 | Sam         |         23 |
|        16 | Mike        |         25 |
|        18 | John        |         27 |
|        20 | David       |         26 |
+-----------+-------------+------------+
6 rows in set (0.00 sec)

这是对 INT 字段执行 MySQL LIKE 比较的查询 −

mysql> select StudentName,StudentAge from ComparisonOnIntField
    -> where cast(StudentId as CHAR) Like '%18%';

以下是输出 −

+-------------+------------+
| StudentName | StudentAge |
+-------------+------------+
| John        |         27 |
+-------------+------------+
1 row in set (0.05 sec)

相关文章