不使用 GROUP BY 來移除重複列行,如何使用 MySQL group by 以單獨的 id 來分組?


為此,你可以使用 DISTINCT 關鍵字。我們首先建立一個表 -

mysql> create table DemoTable1801
     (
     Name varchar(20),
     Score int
     );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable1801 values('John',98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1801 values('John',98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1801 values('John',99);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1801 values('Carol',99);
Query OK, 1 row affected (0.00 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select * from DemoTable1801;

這將產生以下輸出 -

+-------+-------+
| Name  | Score |
+-------+-------+
| John  |    98 |
| John  |    98 |
| John  |    99 |
| Carol |    99 |
+-------+-------+
4 rows in set (0.00 sec)

以下是針對單獨 id 進行分組的查詢 -

mysql> select distinct Name,Score from DemoTable1801;

這將產生以下輸出 -

+-------+-------+
| Name  | Score |
+-------+-------+
| John  |    98 |
| John  |    99 |
| Carol |    99 |
+-------+-------+
3 rows in set (0.00 sec)

更新於:2019-12-24

101 次瀏覽

職業好開始

透過完成課程獲得認證

開始
廣告
© . All rights reserved.