语法如下所示,以跳过重复值并仅从重复值中选择一个-
select min(yourColumnName1),yourColumnName2 from yourTableName group by yourColumnName2;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table doNotSelectDuplicateValuesDemo -> ( -> User_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> User_Name varchar(20) -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下-
mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('John'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Sam'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Mike'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Bob'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('David'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Maxwell'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Bob'); mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Ramit');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from doNotSelectDuplicateValuesDemo;
这是输出-
+---------+-----------+ | User_Id | User_Name | +---------+-----------+ | 1 | John | | 2 | Carol | | 3 | Carol | | 4 | Carol | | 5 | Sam | | 6 | Mike | | 7 | Bob | | 8 | David | | 9 | Maxwell | | 10 | Bob | | 11 | Ramit | +---------+-----------+ 11 rows in set (0.00 sec)
这是跳过重复值并仅从重复值中选择一个的查询-
mysql> select min(User_Id),User_Name from doNotSelectDuplicateValuesDemo group by User_Name;
这是输出-
+--------------+-----------+ | min(User_Id) | User_Name | +--------------+-----------+ | 1 | John | | 2 | Carol | | 5 | Sam | | 6 | Mike | | 7 | Bob | | 8 | David | | 9 | Maxwell | | 11 | Ramit | +--------------+-----------+ 8 rows in set (0.07 sec)