一、基本使用
distinct一般是用來去除查詢結果中的重復記錄的,而且這個陳述句在select、insert、delete和update中只可以在select中使用,具體的語法如下:
select distinct expression[,expression...] from tables [where conditions];
這里的expressions可以是多個欄位,本文的所有操作都是針對如下示例表的:
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`name` varchar(30) NULL DEFAULT NULL ,
`country` varchar(50) NULL DEFAULT NULL ,
`province` varchar(30) NULL DEFAULT NULL ,
`city` varchar(30) NULL DEFAULT NULL ,
PRIMARY KEY (`id`)
)ENGINE=InnoDB;

1.1 只對一列操作
這種操作是最常見和簡單的,如下:
select distinct country from person
結果如下:

1.2 對多列進行操作
select distinct country, province from person
結果如下:

從上例中可以發現,當distinct應用到多個欄位的時候,其應用的范圍是其后面的所有欄位,而不只是緊挨著它的一個欄位,而且distinct只能放到所有欄位的前面,如下陳述句是錯誤的:
SELECT country, distinct province from person; // 該陳述句是錯誤的
拋出錯誤如下:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘DISTINCT province from person’ at line 1
1.3 針對NULL的處理
從1.1和1.2中都可以看出,distinct對NULL是不進行過濾的,即回傳的結果中是包含NULL值的,
1.4 與ALL不能同時使用
默認情況下,查詢時回傳所有的結果,此時使用的就是all陳述句,這是與distinct相對應的,如下:
select all country, province from person
結果如下:

1.5 與distinctrow同義
select distinctrow expression[,expression...] from tables [where conditions];
這個陳述句與distinct的作用是相同的,
1.6 對*的處理
*代表整列,使用distinct對*操作
select DISTINCT * from person
相當于
select DISTINCT id, `name`, country, province, city from person;
文章轉自:https://blog.csdn.net/lmy86263/article/details/73612020
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/56213.html
標籤:MySQL
上一篇:2. InnoDB 存盤引擎-InnoDB體系架構、InnoDB的關鍵特性、Master Thread、insert buffer、兩次寫、自適應哈希索引、異步IO
