在 SQL 中使用“WHERE binary”?


binary 關鍵字可以在 WHERE 子句之後使用,用於進行精確的區分大小寫的匹配。

以下是一個示例:

**案例 1** - 不區分大小寫的匹配

查詢如下:

mysql> select 'joHN'='JOHN' as Result;

輸出如下:

+--------+
| Result |
+--------+
|      1 |
+--------+
1 row in set (0.00 sec)

在上面的示例輸出中,結果為真,而我們知道 joHN 和 JOHN 是兩個不同的單詞。這不是區分大小寫的匹配。

**案例 2** - 如果需要區分大小寫的匹配,請使用 binary 關鍵字。

查詢如下:

mysql> select binary 'joHN'='JOHN' as Result;

輸出如下:

+--------+
| Result |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

讓我們看看另一個查詢:

mysql> select binary 'JOHN'='JOHN' as Result;

輸出如下:

+--------+
| Result |
+--------+
|      1 |
+--------+
1 row in set (0.00 sec)

**注意** - 您可以在建立表時使用 binary 關鍵字,使您的列區分大小寫。

為了理解上述概念,讓我們建立一個表。建立表的查詢如下:

mysql> create table binaryKeywordDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10) binary,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.88 sec)

使用 INSERT 命令在表中插入一些記錄。查詢如下:

mysql> insert into binaryKeywordDemo(Name) values('bOB');
Query OK, 1 row affected (0.15 sec)
mysql> insert into binaryKeywordDemo(Name) values('bob');
Query OK, 1 row affected (0.13 sec)
mysql> insert into binaryKeywordDemo(Name) values('BOB');
Query OK, 1 row affected (0.18 sec)
mysql> insert into binaryKeywordDemo(Name) values('Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into binaryKeywordDemo(Name) values('bOb');
Query OK, 1 row affected (0.15 sec)
mysql> insert into binaryKeywordDemo(Name) values('boB');
Query OK, 1 row affected (0.21 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下:

mysql> select *from binaryKeywordDemo;

輸出如下:

+----+------+
| Id | Name |
+----+------+
|  1 | bOB  |
|  2 | bob  |
|  3 | BOB  |
|  4 | Bob  |
|  5 | bOb  |
|  6 | boB  |
+----+------+
6 rows in set (0.00 sec)

以下是進行精確區分大小寫匹配的查詢:

mysql> select *from binaryKeywordDemo where Name='Bob';

輸出如下:

+----+------+
| Id | Name |
+----+------+
|  4 | Bob  |
+----+------+
1 row in set (0.00 sec)

更新於:2019年7月30日

3K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

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