Postgresql

如何從一個表中獲取與其匹配記錄在 PostgreSQL 中的第二個表中的列的最大值?

  • July 14, 2016

我有兩個表如下:

create table two(grade_id int, edu varchar(20),sortby int);  
alter table two add constraint pk_one primary key(grade_id);
create table one(id int, name varchar(20),grade int);  
alter table one add constraint fk_two_one foreign key(grade) references two(grade_id);

現在我在兩個表中插入一些記錄:

insert into two values(1,'High School',1);
insert into two values(2,'Bachelor',3);
insert into two values(3,'College',2);
insert into two values(4,'Masters',4);
insert into two values(10,'PHD',5);

insert into one values (1,'Ahmad',10);
insert into one values (1,'Ahmad',3);
insert into one values (1,'Ahmad',4);
insert into one values (2,'Ghani',1);
insert into one values (2,'Ghani',3);
insert into one values (2,'Ghani',2);
insert into one values (3,'Fahim',4);
insert into one values (3,'Fahim',1);
insert into one values (3,'Fahim',3);
insert into one values (3,'Fahim',2);  

現在我想從具有最大值idname表中選擇oneedusortby列中的列。 所以我想要的輸出是:two``sortby

id   +    name   +   education  +   sortby  
1    |    Ahmad  |      PHD     |     5  
2    |    Ghani  |      Bachelor|     3  
3    |    Fahim  |      Masters |     4  

任何人請幫忙。

在 Postgres 中,最有效的方法是使用distinct on ()

select distinct on (o.id) o.id, o.name, t.edu, t.sortby
from one o 
 join two t on o.grade = t.grade_id
order by o.id, t.sortby desc  

引用自:https://dba.stackexchange.com/questions/143827