您可以使用GROUP BY命令进行具有不同ID的选择。语法如下-
SELECT *FROM yourTableName GROUP BY yourColumnName;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table DistinctIdDemo -> ( -> Id int, -> Name varchar(20), -> Age int -> );
使用insert命令在表中插入一些记录。在这里,我们添加了具有重复值的ID。
查询如下-
mysql> insert into DistinctIdDemo values(1,'Mike',23); mysql> insert into DistinctIdDemo values(2,'Sam',24); mysql> insert into DistinctIdDemo values(1,'Carol',23); mysql> insert into DistinctIdDemo values(1,'John',28); mysql> insert into DistinctIdDemo values(3,'David',26); mysql> insert into DistinctIdDemo values(2,'Larry',29);
现在让我们显示记录-
mysql> select *from DistinctIdDemo;
以下是输出-
+------+-------+------+ | Id | Name | Age | +------+-------+------+ | 1 | Mike | 23 | | 2 | Sam | 24 | | 1 | Carol | 23 | | 1 | John | 28 | | 3 | David | 26 | | 2 | Larry | 29 | +------+-------+------+ 6 rows in set (0.00 sec)
这是从表中获取具有不同ID的所有记录的查询-
mysql> select *from DistinctIdDemo group by Id;
以下是输出-
+------+-------+------+ | Id | Name | Age | +------+-------+------+ | 1 | Mike | 23 | | 2 | Sam | 24 | | 3 | David | 26 | +------+-------+------+ 3 rows in set (0.00 sec)