PostgreSQL DISTINCT 关键字与SELECT语句结合使用,以消除所有重复记录并仅获取唯一记录.
可能存在某种情况您在表中有多个重复记录.在获取此类记录时,仅获取唯一记录而不是获取重复记录更有意义.
语法
DISTINCT关键字的基本语法消除重复记录如下 :
SELECT DISTINCT column1, column2,.....columnNFROM table_nameWHERE [condition]
示例
考虑表公司,记录如下 :
# select * from COMPANY; id | name | age | address | salary----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000(7 rows)
让我们在此表中再添加两条记录,如下所示;
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)VALUES (8, 'Paul', 32, 'California', 20000.00 );INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)VALUES (9, 'Allen', 25, 'Texas', 15000.00 );
现在,COMPANY表中的记录将是 :
id | name | age | address | salary----+-------+-----+------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 8 | Paul | 32 | California | 20000 9 | Allen | 25 | Texas | 15000(9 rows)
首先,让我们看看以下SELECT查询如何返回重复的工资记录 :
testdb =#SELECT name FROM COMPANY;
这将产生以下结果 :
name------- Paul Allen Teddy Mark David Kim James Paul Allen(9 rows)
现在,让我们使用 DISTINCT 关键字和上面的SELECT查询看结果 :
testdb =#SELECT DISTINCT name FROM COMPANY;
如果我们没有任何重复的条目,这将产生以下结果;
name------- Teddy Paul Mark David Allen Kim James(7 rows)