在 INT 欄位上執行 MySQL LIKE 比較?


您需要使用 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)

以下是執行 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)

更新時間: 2019 年 7 月 30 日

593 次檢視

開啟您的 事業

透過完成課程獲取認證

開始學習
廣告
© . All rights reserved.