PostgreSQL使用LIMIT 1连接两个表

时间:2016-01-17 16:15:26

标签: sql postgresql left-join

我有两张桌子:

第一张表“人物”

action

第二个表“会议”

id  |  name   |
---------------
1   |  peter  |
3   |  martin |
5   |  lucy   |

我需要以某种方式从每个人(或选定的)的“会议”表中获取最后日期。结果表必须按名称排序。我想,它可能是这样的,但是LEFT JOIN中的WHERE子句不能使用:

id  |  date       | id_persons |
--------------------------------
1   |  2014-12-08 |     1      |
2   |  2013-05-10 |     2      |
3   |  2015-08-25 |     1      |
4   |  2016-10-18 |     1      |
5   |  2012-01-01 |     3      |
6   |  2016-09-28 |     5      |

所以我开始使用DISTINCT并且它有效,但我认为这不是一个好主意:

SELECT meetings.id, meetings.date, persons.name FROM persons
  LEFT JOIN (SELECT meetings.date, meetings.id, meetings.id_persons FROM
           meetings WHERE persons.id = meetings.id_persons ORDER BY
           meetings.date DESC LIMIT 1) m ON m.id_persons = persons.id 
WHERE persons.id < 6 ORDER BY persons.name

结果我需要的是:

SELECT * FROM 
    (SELECT DISTINCT ON (persons.id) persons.id, persons.name, 
         m.date, m.id FROM persons
         LEFT JOIN (SELECT meetings.id, meetings.date, meetings.id_persons 
             FROM meetings ORDER BY meetings.date DESC) m 
             ON m.id_persons = persons.id
     WHERE persons.id < 6 ORDER BY persons.id) p 
ORDER BY p.name

你能帮我找到更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

在Postgres中,最简单的方法可能是distinct on

select distinct on (p.id) p.*, m.*
from persons p left join
     meetings m
     on m.id_persons = p.id
order by p.id, m.date desc;

注意:distinct on特定于Postgres。