如果記錄包含空格,如何正確使用 MySQL DISTINCT 的方法?


要獲取包括空格在內的 DISTINCT,可以使用以下語法 -

SELECT DISTINCT replace(yourColumnName,' ','') FROM yourTableName;

我們首先建立一張表

mysql>create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20)
);
Query OK, 0 rows affected (0.63 sec)

使用 insert 命令在表中插入一些記錄 -

mysql>insert into DemoTable(Name) values('John ');
Query OK, 1 row affected (0.14 sec)
mysql>insert into DemoTable(Name) values(' John ');
Query OK, 1 row affected (0.14 sec)
mysql>insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.09 sec)
mysql>insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.15 sec)
mysql>insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.22 sec)
mysql>insert into DemoTable(Name) values(' Sam');
Query OK, 1 row affected (0.14 sec)
mysql>insert into DemoTable(Name) values('Mike ');
Query OK, 1 row affected (0.12 sec)
mysql>insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.17 sec)

以下是使用 select 語句從表中顯示所有記錄的查詢

mysql>select *from DemoTable;

這將產生以下輸出 -

+----+-----------+
| Id | Name      |
+----+-----------+
| 1  | John      |
| 2  | John      |
| 3  | John      |
| 4  | Sam       |
| 5  | Carol     |
| 6  | Sam       |
| 7  | Mike      |
| 8  | David     |
+----+-----------+
8 rows in set (0.00 sec)

這是獲取包括空格在內 DISTINCT 的查詢

mysql>SELECT DISTINCT replace(Name,' ','') FROM DemoTable;

這將產生以下輸出 -

+----------------------+
| replace(Name,' ','') |
+----------------------+
| John                 |
| Sam                  |
| Carol                |
| Mike                 |
| David                |
+----------------------+
5 rows in set (0.00 sec)

更新於: 30-7-2019

136 次瀏覽

開啟職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.