应用一种条件左连接

问题描述 投票:0回答:1

我有表 t1 和 t2,都有两列。两个表都包含客户及其交易数据。我想要那些在 t1 但不在 t2 并且在 t2 至少有 1 笔交易的客户的客户和交易代码。

t1

cust_code_1 trans_code_1
1 a
1 b
1 c
1 d
1 e
2 a
2 b
2 c
3
3 j
3 k
3 l
. .
. .
. .
. .

t2

cust_code_2 trans_code_2
1 a
1 b
1 c
2 b
CREATE TABLE t1 
(
    cust_code_1 VARCHAR(512),
    trans_code_1    VARCHAR(512)
);

INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('1', 'a');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('1', 'b');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('1', 'c');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('1', 'd');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('1', 'e');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('2', 'a');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('2', 'b');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('2', 'c');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('3', 'i');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('3', 'j');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('3', 'k');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('3', 'l');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('.', '.');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('.', '.');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('.', '.');
INSERT INTO t1 (cust_code_1, trans_code_1) VALUES ('.', '.');
CREATE TABLE t2 
(
    cust_code_2 VARCHAR(512),
    trans_code_2    VARCHAR(512)
);

INSERT INTO t2 (cust_code_2, trans_code_2) VALUES ('1', 'a');
INSERT INTO t2 (cust_code_2, trans_code_2) VALUES ('1', 'b');
INSERT INTO t2 (cust_code_2, trans_code_2) VALUES ('1', 'c');
INSERT INTO t2 (cust_code_2, trans_code_2) VALUES ('2', 'b');

预期产出

cust_code_1 trans_code_1 cust_code_2 trans_code_2
1 d
1 e
2 a
2 c

我得到的输出

cust_code_1 trans_code_1 cust_code_2 trans_code_2
1 d
1 e
2 a
2 c
3
3 j
3 k
3 l
. . . .
. . . .
. . . .
select * from t1 left join t2
on t1.cust_code_1=t2.cust_code_2
    and t1.trans_code_1=t2.trans_code_2 
where t2.cust_code_2 is null

我不想在输出中使用 cust_code_1 3。我想要 left join 的输出,但 cust_code_2 应该可用。 因为我有数百万条记录,但我只需要那些在 t2 中不可用的 Cust code = 1 和 Cust code = 2 的交易。

如何获得预期的输出?

sql postgresql left-join
1个回答
0
投票

您可以通过仅将以下条件附加到 where 子句来过滤掉不需要的记录:

and t1.cust_code_1 in (select tt2.cust_code_2 from t2 as tt2);

因此,您的结果将仅包含在 cust_code_2 列中具有值的记录。

这是完整的 sql:

select * 
from t1 left join t2 on t1.cust_code_1 = t2.cust_code_2
and t1.trans_code_1 = t2.trans_code_2 
where t2.cust_code_2 is null 
    and t1.cust_code_1 in (select tt2.cust_code_2 from t2 as tt2);

您可以在这个 SQL Fiddle 中尝试它。

© www.soinside.com 2019 - 2024. All rights reserved.