SELECT DISTINCT 可用來給予不同的值。用它來刪除重複的記錄並 它也可以與聚合函數一起使用。例如:MAX、AVG等。這個都可以應用 在單一列上。
現在,我正在建立一個表格以對列使用 SELECT DISTINCT。建立一個表 CREATE 指令的說明 -
mysql> CREATE TABLE DistinctDemo -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.64 sec)
插入記錄 −
mysql> INSERT into DistinctDemo values(1,'John'); Query OK, 1 row affected (0.17 sec) mysql> INSERT into DistinctDemo values(2,'John'); Query OK, 1 row affected (0.18 sec) mysql> INSERT into DistinctDemo values(3,'Bob'); Query OK, 1 row affected (0.17 sec) mysql> INSERT into DistinctDemo values(4,'John'); Query OK, 1 row affected (0.15 sec) mysql> INSERT into DistinctDemo values(5,'David'); Query OK, 1 row affected (0.17 sec) mysql> INSERT into DistinctDemo values(6,'Bob'); Query OK, 1 row affected (0.16 sec)
借助 SELECT 指令顯示所有記錄。查詢如下 -
mysql> SELECT * from DistinctDemo;
執行上述查詢後,我們將獲得以下輸出 −
+------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | John | | 3 | Bob | | 4 | John | | 5 | David | | 6 | Bob | +------+-------+ 6 rows in set (0.00 sec)
上面,我們有六個記錄,其中John和Bob是重複的。我們可以應用DISTINCT來 刪除重複記錄。語法如下−
SELECT distinctcolumn_name from yourTableName order by column_name;
現在,我正在應用上述查詢來刪除重複項-
mysql> SELECT distinct name from DistinctDemo;
以下是輸出
+-------+ | name | +-------+ | John | | Bob | | David | +-------+ 3 rows in set (0.00 sec)
Select group by 可用於從不同列獲取資料並分組為一個或多個 column. This can also be applied with aggregate function.For Example:SUM,AVG etc.
Firstly, I am creating a table with the CREATE 指令的幫助 -
column. 這也可以與聚合函數一起使用。例如:SUM,AVG等。首先,我正在使用CREATE指令建立一個表格−
mysql> CREATE table GroupDemo1 -> ( -> id int, -> name varchar(100), -> address varchar(100) -> ); Query OK, 0 rows affected (0.68 sec)
建立表格後,我將記錄插入到表中,如下所示−
mysql> INSERT into GroupDemo1 values(1,'John','US'); Query OK, 1 row affected (0.18 sec) mysql> INSERT into GroupDemo1 values(2,'Bob','UK'); Query OK, 1 row affected (0.13 sec) mysql> INSERT into GroupDemo1 values(3,'David','US'); Query OK, 1 row affected (0.12 sec) mysql> INSERT into GroupDemo1 values(4,'David','US'); Query OK, 1 row affected (0.15 sec)
現在,我們可以使用SELECT指令顯示所有記錄−
mysql> SELECT * from GroupDemo1;
以下是輸出-
+------+-------+---------+ | id | name | address | +------+-------+---------+ | 1 | John | US | | 2 | Bob | UK | | 3 | David | US | | 4 | David | US | +------+-------+---------+ 4 rows in set (0.00 sec)
我將套用GROUP BY 來了解相同位址的出現次數。這裡是 語法 −
SELECT column_name1,......N aggregate function( ) from yourTableName group by column_name;
讓我們將上述語法應用於 GROUP BY -
mysql> SELECT address, count(*) from GroupDemo1 group by address;
以下是輸出 -
+---------+----------+ | address | count(*) | +---------+----------+ | US | 3 | | UK | 1 | +---------+----------+ 2 rows in set (0.00 sec)
以上是MySQL 中 SELECT DISTINCT 與 GROUP BY 的差異?的詳細內容。更多資訊請關注PHP中文網其他相關文章!