我有以下代码。
CREATE TABLE "s"."t1"
(
"c1" BigSerial PRIMARY KEY,
"c2" BigInt NOT NULL
)
WITH (OIDS=FALSE);
INSERT INTO s.t1 (c2) VALUES (100);
INSERT INTO s.t1 (c2) VALUES (200);
CREATE TABLE "s"."t2"
(
"c1" BigSerial PRIMARY KEY,
"c2" BigInt NOT NULL,
"c3" BigInt NOT NULL,
CONSTRAINT "fk1" FOREIGN KEY (c2) REFERENCES s.t1 (c1) ON DELETE SET NULL ON UPDATE CASCADE
)
WITH (OIDS=FALSE);
INSERT INTO s.t2 (c2, c3) VALUES (1, 2000);
INSERT INTO s.t2 (c2, c3) VALUES (1, 3000);
SELECT t1.c1
FROM s.t1 t1
WHERE t1.c1 NOT IN
(SELECT DISTINCT t1.c1 FROM s.t1 t1
INNER JOIN s.t2 AS t2 on t2.c2 = t1.c1);
输出为2。
我正在尝试查看t1
(c1
)的列,并检查c1
中是否有任何不属于t2
的值({{1} }})。
使用count或outer join有更好的方法吗?
答案 0 :(得分:1)
使用except
:
select c1 from t1
except
select c2 from t2;
答案 1 :(得分:0)
此问题称为反连接模式,您可以尝试使用left join
和is null
检查,例如:
SELECT t1.c1
FROM s.t1 t1
LEFT JOIN s.t2 t2 ON t2.c2 = t1.c1
WHERE t2.c2 IS NULL