扫码一下
查看教程更方便
postgresql distinct关键字与 select 语句结合使用以消除所有重复记录并仅获取唯一记录。
我们平时在操作数据时,有可能出现一种情况,在一个表中有多个重复的记录,当提取这样的记录时,distinct 关键字就显得特别有意义,它只获取唯一一次记录,而不是获取重复记录。
用于去除重复记录的 distinct 关键字的基本语法如下:
select distinct column1, column2,.....columnn
from table_name
where [condition]
创建 ,数据内容如下:
jiyik_db=# 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 );
现在数据如下:
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)
接下来我们找出 company 表中的所有 name:
jiyik_db=# select name from company;
得到结果如下:
name
-------
paul
allen
teddy
mark
david
kim
james
paul
allen
(9 rows)
现在我们在 select 语句中使用 distinct 子句:
jiyik_db=# select distinct name from company;
结果如下:
name
-------
teddy
paul
mark
david
allen
kim
james
(7 rows)
从结果可以看到,重复数据已经被删除。