如果记录包含空格,如何正确使用 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)
广告