MySQL 忽略大小寫的 DISTINCT?


如果您想要區分大小寫的 distinct,您需要使用 UPPER() 或 LOWER()。

案例 1: 使用 UPPER()。

語法如下

SELECT DISTINCT UPPER(yourColumnName) FROM yourTableName;

案例 2: 使用 LOWER()。

語法如下

SELECT DISTINCT LOWER(yourColumnName) FROM yourTableName;

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

mysql> create table CaseInsensitiveDistinctDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> UserEmailId varchar(30),
   -> UserPassword varchar(10),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.64 sec)

現在,您可以使用 insert 命令在表中插入一些記錄。該查詢如下

mysql> insert into CaseInsensitiveDistinctDemo(UserEmailId,UserPassword) values('John@gmail.com','john123');
Query OK, 1 row affected (0.15 sec)
mysql> insert into CaseInsensitiveDistinctDemo(UserEmailId,UserPassword) values('john@gmail.com','654321');
Query OK, 1 row affected (0.43 sec)
mysql> insert into CaseInsensitiveDistinctDemo(UserEmailId,UserPassword) values('Mike@gmail.com','999999');
Query OK, 1 row affected (0.14 sec)
mysql> insert into CaseInsensitiveDistinctDemo(UserEmailId,UserPassword) values('mike@gmail.com','334556');
Query OK, 1 row affected (0.16 sec)
mysql> insert into CaseInsensitiveDistinctDemo(UserEmailId,UserPassword) values('Carol@gmail.com','1010101');
Query OK, 1 row affected (0.13 sec)
mysql> insert into CaseInsensitiveDistinctDemo(UserEmailId,UserPassword) values('Larry@gmail.com','12345678');
Query OK, 1 row affected (0.20 sec)

使用 select 語句從表中顯示所有記錄。該查詢如下

mysql> select *from CaseInsensitiveDistinctDemo;

以下是輸出

+----+-----------------+--------------+
| Id | UserEmailId     | UserPassword |
+----+-----------------+--------------+
|  1 | John@gmail.com  | john123      |
|  2 | john@gmail.com  | 654321       |
|  3 | Mike@gmail.com  | 999999       |
|  4 | mike@gmail.com  | 334556       |
|  5 | Carol@gmail.com | 1010101      |
|  6 | Larry@gmail.com | 12345678     |
+----+-----------------+--------------+
6 rows in set (0.00 sec)

以下是選擇忽略大小寫 distinct 的查詢。

案例 1: 使用 UPPER()。該查詢如下

mysql> select distinct upper(UserEmailId) from CaseInsensitiveDistinctDemo;

以下是輸出

+--------------------+
| upper(UserEmailId) |
+--------------------+
| JOHN@GMAIL.COM     |
| MIKE@GMAIL.COM     |
| CAROL@GMAIL.COM    |
| LARRY@GMAIL.COM    |
+--------------------+
4 rows in set (0.06 sec)

案例 2: 使用 LOWER()。該查詢如下

mysql> select distinct lower(UserEmailId) from CaseInsensitiveDistinctDemo;

以下是輸出

+--------------------+
| lower(UserEmailId) |
+--------------------+
| john@gmail.com     |
| mike@gmail.com     |
| carol@gmail.com    |
| larry@gmail.com    |
+--------------------+
4 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

5K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

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