postgresql加入2个表

时间:2012-02-27 11:37:19

标签: sql postgresql join

我有2个表tab1和tab2,tab2(tab1_id)引用tab1(id)

tab2具有tab1(id)

的不同值

我需要一个连接,它将tab1与tab2中的action列连接, 和最新的id。

tab1 :-


 id | user_file_id |    created_date     |    modified_date    
----+--------------+---------------------+---------------------
  2 |          102 | 2012-01-12 01:23:46 | 2012-03-04 16:52:28
  4 |          104 | 2012-01-12 15:45:10 | 2012-01-15 02:23:40
  6 |          106 | 2012-01-18 00:14:34 | 2012-01-24 20:17:49
  7 |          107 | 2012-02-02 01:07:14 | 2012-04-17 09:29:17
  8 |          108 | 2012-02-15 13:16:24 | 2012-03-26 10:30:51
  9 |          109 | 2012-02-20 18:08:48 | 2012-04-09 06:14:58
 10 |          110 | 2012-02-24 20:49:10 | 2012-03-23 11:36:41
 11 |          111 | 2012-03-05 22:38:14 | 2012-03-16 04:29:35
(8 rows)


tab2:-

 id | action | tab1_id 
----+--------+---------
  1 |      1 |       2
  3 |      2 |       2
  4 |      1 |       2
  5 |      2 |       2
  6 |      1 |       2
  7 |      3 |       2
  2 |      1 |       4
  8 |      1 |       6
  9 |      1 |       7
 10 |      1 |       8
 11 |      1 |       9
 12 |      1 |      10
 13 |      1 |      11
(13 rows)

将tab1和tab2连接起来以获得输出: -

id | user_file_id |    created_date     |    modified_date    | action 
----+--------------+---------------------+---------------------+--------
  2 |          102 | 2012-01-12 01:23:46 | 2012-03-04 16:52:28 |      3
  4 |          104 | 2012-01-12 15:45:10 | 2012-01-15 02:23:40 |      1
  6 |          106 | 2012-01-18 00:14:34 | 2012-01-24 20:17:49 |      1
  7 |          107 | 2012-02-02 01:07:14 | 2012-04-17 09:29:17 |      1
  8 |          108 | 2012-02-15 13:16:24 | 2012-03-26 10:30:51 |      1
  9 |          109 | 2012-02-20 18:08:48 | 2012-04-09 06:14:58 |      1
 10 |          110 | 2012-02-24 20:49:10 | 2012-03-23 11:36:41 |      1
 11 |          111 | 2012-03-05 22:38:14 | 2012-03-16 04:29:35 |      1
(8 rows)

2 个答案:

答案 0 :(得分:2)

尝试:

select t1.*, t2.action
from tab1 t1
join (select t.*,
             row_number() over (partition by tab1_id order by id desc) rn
      from tab2 t) t2
  on t1.id = t2.tab1_id and t2.rn = 1

如果要允许tab1上的行没有在tab2上记录任何操作,请将连接更改为左连接。

答案 1 :(得分:1)

SELECT tab1.*, t2.action
FROM  tab1
JOIN (
    SELECT DISTINCT ON (tab1_id) tab1_id
         , first_value(action) OVER (PARTITION BY tab1_id
                                     ORDER BY id DESC) AS action
    FROM   tab2
    ) t2 ON tab1.id = t2.tab1_id

@Mark已经提到了替代LEFT JOIN