在mysql中,distinct關(guān)鍵字用于過濾重復(fù)數(shù)據(jù),它可以對(duì)數(shù)據(jù)表中一個(gè)或多個(gè)字段重復(fù)的數(shù)據(jù)進(jìn)行過濾,只返回其中的一條數(shù)據(jù)給用戶;distinct關(guān)鍵字需要和SELECT語句一起使用,語法“SELECT DISTINCT column1, column2, … FROM table_name; ”。

程序員必備接口測試調(diào)試工具:立即使用
Apipost = Postman + Swagger + Mock + Jmeter
Api設(shè)計(jì)、調(diào)試、文檔、自動(dòng)化測試工具
后端、前端、測試,同時(shí)在線協(xié)作,內(nèi)容實(shí)時(shí)同步
本教程操作環(huán)境:windows7系統(tǒng)、mysql8版本、Dell G3電腦。
在 MySQL 中使用 SELECT 語句執(zhí)行簡單的數(shù)據(jù)查詢時(shí),返回的是所有匹配的記錄。如果表中的某些字段沒有唯一性約束,那么這些字段就可能存在重復(fù)值。為了實(shí)現(xiàn)查詢不重復(fù)的數(shù)據(jù),MySQL 提供了 DISTINCT 關(guān)鍵字。
DISTINCT 關(guān)鍵字的主要作用就是對(duì)數(shù)據(jù)表中一個(gè)或多個(gè)字段重復(fù)的數(shù)據(jù)進(jìn)行過濾,只返回其中的一條數(shù)據(jù)給用戶。
DISTINCT 關(guān)鍵字的語法格式為:
SELECT DISTINCT column1, column2, ... FROM table_name;
其中,“column”為需要消除重復(fù)記錄的一個(gè)或多個(gè)字段名稱,多個(gè)字段時(shí)用逗號(hào)隔開。
使用 DISTINCT 關(guān)鍵字時(shí)需要注意以下幾點(diǎn):
-
DISTINCT 關(guān)鍵字只能在 SELECT 語句中使用。
-
在對(duì)一個(gè)或多個(gè)字段去重時(shí),DISTINCT 關(guān)鍵字必須在所有字段的最前面。
-
如果 DISTINCT 關(guān)鍵字后有多個(gè)字段,則會(huì)對(duì)多個(gè)字段進(jìn)行組合去重,也就是說,只有多個(gè)字段組合起來完全是一樣的情況下才會(huì)被去重。
演示數(shù)據(jù)庫
以下是Northwind示例數(shù)據(jù)庫中“Customers”表的選擇:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constituciуn 2222 | Mйxico D.F. | 05021 | Mexico |
| 3 | Antonio Moreno Taquerнa | Antonio Moreno | Mataderos 2312 | Mйxico D.F. | 05023 | Mexico |
| 4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
| 5 | Berglunds snabbkцp | Christina Berglund | Berguvsvдgen 8 | Luleе | S-958 22 | Sweden |
沒有使用DISTINCT的SELECT實(shí)例
以下SQL語句從“Customers”表中的“Country”列中選擇ALL(包括重復(fù)項(xiàng))值:
SELECT Country FROM Customers;

SELECT DISTINCT實(shí)例
1、僅從“Customers”表中的“Country”列中選擇DISTINCT值:
SELECT DISTINCT Country FROM Customers;

2、列出了不同 “Country” 的數(shù)量:
SELECT COUNT(DISTINCT Country) FROM Customers;

注意:上面的示例在Firefox和Microsoft Edge中不起作用!因?yàn)镸icrosoft Access數(shù)據(jù)庫不支持COUNT(DISTINCT column_name)。Firefox和Microsoft Edge在我們的示例中使用Microsoft Access。
【
站長資訊網(wǎng)