如何将记录值传递给子查询(PostgreSQL)?

时间:2016-01-28 15:01:32

标签: database postgresql

我有两个文件:apt和appointment_history。第二个文件有多个 在apt中引用单个记录的记录。

如何仅从子查询中获取引用apt中记录的约会历史记录中的最后一条记录?

编辑#1:问题不在于如何分组,而在于如何将外部值(appointment_recid)传递到子查询中,而不将整个appointment_history文件分组到未使用的appointment_recid上。所以我不认为这是一个重复的问题。 (虽然是一个noobie,它可能会变成相同的。)

PostgreSQL 9.3

  

错误:对表" apt"的FROM子句条目的无效引用SQL   state:42P01提示:表" apt"有一个条目,但它不能   从查询的这一部分引用。

git

TIA

2 个答案:

答案 0 :(得分:1)

select apt.*, h.* 
    from apt 
    join appointment_history h 
      on (h.appointment_recid = apt.appointment_recid)
    join ( 
           SELECT appointment_recid, max(tposted) as tposted 
           FROM appointment_history a
           GROUP BY  appointment_recid  -- ADD GROUP BY 
         ) currenthx 
      on currenthx.tposted = h.tposted
     and currenthx.appointment_recid = a.appointment_recid   -- JOIN OUTSIDE

请求

select apt.*, h.* 
    from apt 
    join appointment_history h 
      on (h.appointment_recid = apt.appointment_recid)
    join ( 
           SELECT appointment_recid, max(tposted) as tposted 
           FROM appointment_history a
           JOIN apt ap
               on (h.appointment_recid = ap.appointment_recid)               
           GROUP BY  appointment_recid  -- ADD GROUP BY 
         ) currenthx 
      on currenthx.tposted = h.tposted
     and currenthx.appointment_recid = a.appointment_recid   -- JOIN OUTSIDE

答案 1 :(得分:1)

如果没有详细的表格信息,这可能会解决您的问题:

SELECT apt.*, h.* 
FROM apt
JOIN (
  SELECT <columns>, max(tposted) AS tposted 
  FROM appointment_history
  GROUP BY <columns>) h USING (appointment_recid);