PostgreSQL的DISTINCT关键字用于与SELECT语句消除所有重复的记录,并获取唯一记录。
www.gitbook.net
有可能的情况下,当你有多个重复的表中的记录。虽然取这样的记录,它更有意义,获取唯一的记录,而不是获取重复记录。 gitbook.net
DISTINCT关键字消除重复记录的基本语法如下: www.gitbook.net
SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition]www.gitbook.net
考虑表COMPANY 有如下记录:
www.gitbook.net
# 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)www.gitbook.net
让我们添加两个记录到这个表如下: gitbook.net
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 );gitbook.net
现在,该公司表中的记录将是:
www.gitbook.net
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)
gitbook.net
首先,让我们来看看下面的SELECT查询返回重复的工资记录:
testdb=# SELECT name FROM COMPANY;gitbook.net
这将产生以下结果:
name ------- Paul Allen Teddy Mark David Kim James Paul Allen (9 rows)gitbook.net
现在,让我们使用DISTINCT关键字与上述SELECT查询看到的结果: www.gitbook.net
testdb=# SELECT DISTINCT name FROM COMPANY;gitbook.net
我们没有任何重复的条目,这将产生以下结果: gitbook.net
name ------- Teddy Paul Mark David Allen Kim James (7 rows)www.gitbook.net