📜  PostgreSQL-DISTINCT关键字

📅  最后修改于: 2020-11-26 06:25:59             🧑  作者: Mango


PostgreSQL DISTINCT关键字与SELECT语句结合使用,以消除所有重复记录并仅获取唯一记录。

当表中有多个重复记录时,可能会出现这种情况。在获取此类记录时,仅获取唯一记录而不是获取重复记录更为有意义。

句法

消除重复记录的DISTINCT关键字的基本语法如下-

SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]

考虑具有以下记录的表COMPANY-

# 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)

现在,让我们在上面的SELECT查询中使用DISTINCT关键字,然后查看结果-

testdb=# SELECT DISTINCT name FROM COMPANY;

如果我们没有任何重复的条目,这将产生以下结果-

name
-------
 Teddy
 Paul
 Mark
 David
 Allen
 Kim
 James
(7 rows)