MySQL 使用 distinct id 選擇 *?


針對 distinct id 選擇時,您可以使用 GROUP BY 命令。語法如下 −

SELECT *FROM yourTableName GROUP BY yourColumnName;

為理解以上語法,讓我們建立一個表。建立表的查詢如下 −

mysql> create table DistinctIdDemo
   -> (
   -> Id int,
   -> Name varchar(20),
   -> Age int
   -> );
Query OK, 0 rows affected (1.03 sec)

使用插入命令在表中插入一些記錄。在此處,我們已新增具有重複值的 ID。

查詢如下 −

mysql> insert into DistinctIdDemo values(1,'Mike',23);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DistinctIdDemo values(2,'Sam',24);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DistinctIdDemo values(1,'Carol',23);
Query OK, 1 row affected (0.15 sec)

mysql> insert into DistinctIdDemo values(1,'John',28);
Query OK, 1 row affected (0.33 sec)

mysql> insert into DistinctIdDemo values(3,'David',26);
Query OK, 1 row affected (0.22 sec)

mysql> insert into DistinctIdDemo values(2,'Larry',29);
Query OK, 1 row affected (0.20 sec)

現在,讓我們顯示記錄 −

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)

以下是針對具有 distinct 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)

更新於: 2020 年 6 月 30 日

2000+ 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.