如果记录包含空格,MySQL DISTINCT 能否正常工作?
mysqlmysqli database
要获取包括空格在内的不同值,您可以使用以下语法 −
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)
以下是获取包括空格在内的不同值的查询:
mysql>SELECT DISTINCT replace(Name,' ','') FROM DemoTable;
这将产生以下输出 −
+----------------------+ | replace(Name,' ','') | +----------------------+ | John | | Sam | | Carol | | Mike | | David | +----------------------+ 5 rows in set (0.00 sec)