PostgreSQL - 获取与一个查询的关系的第一个和最后一个记录

时间:2018-03-29 10:23:49

标签: sql postgresql

我的数据库中有以下架构:

   CREATE TABLE users (
        id integer NOT NULL
    );   

   CREATE TABLE survey_results (
        id integer NOT NULL,
        name text,
        user_id integer,
        created_at timestamp without time zone
    );

    INSERT INTO users (id)
        VALUES (1);    

    INSERT INTO survey_results (id, name, user_id, created_at)
        VALUES (1, 'TEST 1', 1, now());

    INSERT INTO survey_results (id, name, user_id, created_at)
        VALUES (2, 'TEST 2', 1, now());

    INSERT INTO survey_results (id, name, user_id, created_at)
        VALUES (3, 'TEST 3', 1, now());

现在我想在一个查询中获取第一个和最后一个用户survey_result的名称,因此结果应该如下所示

id   first   last

1    TEST1  TEST2

我如何在PostgreSQL中执行此操作?

这是具有此架构的sqlfiddle:https://www.db-fiddle.com/f/aC2DrJXqmJc1ZLkdEjLnht/0

2 个答案:

答案 0 :(得分:1)

它很漂亮!

select 
u.id as user_id,
(select name from survey_results where user_id = u.id order by created_at asc limit 1) as first,
(select name from survey_results where user_id = u.id order by created_at desc limit 1) as last
from users u 

我使它更漂亮(使用连接而不是相关的子类),这可以提供额外的功能。

select 
u.id
,min.name as minName
,min.created_at as minDate
,max.name as maxName
,max.created_at as maxDate
from users u 
join (select * from survey_results  order by created_at asc limit 1  ) as min on min.user_id = u.id
join (select * from survey_results  order by created_at desc limit 1  ) as max on min.user_id = u.id

答案 1 :(得分:1)

这样的事情:

created_at

但是,如果第一个和最后一个调查具有相同的ParentC

,则无效