Postgresql-仅在多个表中合并数据

时间:2017-10-08 17:50:45

标签: postgresql

我正在寻找一种在Id上加入两列的方法。 Table2 id具有重复的id。我需要过滤Id,其中test具有最小值并且关联test2,但其余部分则丢弃。 当我使用INNER JOIN和LEFT JOIN时,我将获得多个ID以及测试。

#!/usr/bin/env python3.6
import sys
s1 = str(sys.argv[1])
alpha = "abcdefghijklmnopqrstuvwxyz"
subs = []


def longest_substring(s1):
    for i in range(len(alpha)):
        for k in range(len(alpha)):
            if alpha[i:k] in s1:
                subs.append(alpha[i:k])
    return max(subs, key=len)


print("Longest substring in alphabetical order:", longest_substring(s1))

期望的输出

Sample data
Table1

        +----+--------+-----+
        | Id | weight | seq |
        +----+--------+-----+
        | 58 | 180    | 34  |
        +----+--------+-----+
        | 36 | 139    | 33  |
        +----+--------+-----+
        | 53 | 150    | 91  |
        +----+--------+-----+

Table2
+----+------+-------+
| Id | test | test2 |
+----+------+-------+
| 58 | 90   | 12    |
+----+------+-------+
| 36 | 45   | 19    |
+----+------+-------+
| 36 | 23   | 24    |
+----+------+-------+
| 53 | 20   | 22    |
+----+------+-------+

我的输出

+----+--------+-----+------+-------+
| Id | weight | seq | test | test2 |
+----+--------+-----+------+-------+
| 58 | 180    | 34  | 90   | 12    |
+----+--------+-----+------+-------+
| 36 | 139    | 33  | 23   | 24    |
+----+--------+-----+------+-------+
| 53 | 150    | 91  | 20   | 22    |
+----+--------+-----+------+-------+

 SELECT
    table1.id, 
    table1.weight, 
    table1.seq, 
    table2.id, 
    table2.test, 
    table2.test2
    FROM 
    public.table1
    LEFT JOIN public.table2 
    ON table1.id = table2.id;

SELECT 
table1.id, 
table1.weight, 
table1.seq, 
table2.id, 
table2.test, 
table2.test2
FROM 
public.table1
INNER JOIN public.table2 
ON table1.id = table2.id;

1 个答案:

答案 0 :(得分:0)

您可以使用row_number()窗口函数获取具有最小test值的行:

SELECT t1.*
FROM   table1 t1
JOIN   (SELECT id, test, test2, RANK() OVER (PARTITION BY id ORDER BY test ASC) rk
        FROM   table2) t2 ON t1.id = t2.id AND rk = 1