比较两个表的两个变量,得到这两个变量在单行中的值在第一个表中而不在第二个表中的行



我对PostgreSQL的代码很感兴趣。

让我们创建两个表:
create table tbl_1 (id bigserial, var_1 text, var_2 text, compare_1 text, compare_2 text);
insert into tbl_1 (var_1, var_2, compare_1, compare_2) values
('a', 'a', 1, 11),('a', 'a', 2, 22),('a', 'a', 4, 44),('a', 'a', 5, 55); 
create table tbl_2 (id bigserial, var_1 text, var_2 text, compare_1 text, compare_2 text);
insert into tbl_2 (var_1, var_2, compare_1, compare_2) values
('b', 'b', 1, 11),('b', 'b', 2, 22),('b', 'b', 4, 77),('a', 'a', 6, 66); 

tbl_1看起来像:

id  var_1  var_2  compare_1  compare_2
1   "a"    "a"    "1"        "11"
2   "a"    "a"    "2"        "22"
3   "a"    "a"    "4"        "44"
4   "a"    "a"    "5"        "55"

tbl_2看起来像:

id  var_1  var_2  compare_1  compare_2
1   "b"    "b"    "1"        "11"
2   "b"    "b"    "2"        "22"
3   "b"    "b"    "4"        "77"
4   "a"    "a"    "6"        "66"

现在我需要得到tbl_1的所有行,其中compare_1compare_2变量值在单行上不存在于tbl_2中,compare_1compare_2变量值在单行上。因此,我想得到的结果看起来像:

id  var_1  var_2  compare_1  compare_2
3   "a"    "a"    "4"        "44"
4   "a"    "a"    "5"        "55"

使用NOT IN:

SELECT * FROM tbl_1
WHERE (compare_1, compare_2) NOT IN (SELECT compare_1, compare_2 FROM tbl_2)

查看演示

您可以使用not exists:

select t1.*
from tbl_1 t1 
where not exists (select 1
from tbl_2 t2
where t2.compare_1 = t1.compare_1 and
t2.compare_2 = t2.compare_2
);

最新更新