我有4张桌子,
A,B,C,D
A有列Aid, B有列Aid, C有列Aid, D有列Aid
(援助是所有4个表中的共同栏目)
现在我想从A表中获取B或C或D中不存在的行 任何人都可以让我知道SQL查询。
答案 0 :(得分:3)
准备示例数据:
CREATE TABLE A (aid int);
CREATE TABLE B (aid int);
CREATE TABLE C (aid int);
CREATE TABLE D (aid int);
INSERT INTO A VALUES (1);
INSERT INTO A VALUES (2);
INSERT INTO A VALUES (3);
INSERT INTO A VALUES (4);
INSERT INTO A VALUES (5);
INSERT INTO B VALUES (2);
INSERT INTO C VALUES (3);
INSERT INTO D VALUES (4);
查询:
SELECT aid
FROM A
LEFT OUTER JOIN B on A.aid=B.aid
LEFT OUTER JOIN C on A.aid=C.aid
LEFT OUTER JOIN D on A.aid=D.aid
WHERE B.aid IS NULL AND C.aid IS NULL AND D.aid IS NULL;
结果为1
和5
。
答案 1 :(得分:3)
您可以使用MINUS
运算符:
SELECT Aid FROM A
MINUS
SELECT Aid FROM B
MINUS
SELECT Aid FROM C
MINUS
SELECT Aid FROM D
示例强>
CREATE TABLE A ( Aid, Value ) AS
SELECT 1, '1' FROM DUAL UNION ALL
SELECT 1, '2' FROM DUAL UNION ALL
SELECT 2, '3' FROM DUAL UNION ALL
SELECT NULL, '4' FROM DUAL UNION ALL
SELECT 3, '5' FROM DUAL;
CREATE TABLE B ( Aid, BValue ) AS
SELECT 1, '3' FROM DUAL;
CREATE TABLE C ( Aid, CValue ) AS
SELECT 4, '7' FROM DUAL;
CREATE TABLE D ( Aid, DValue ) AS
SELECT NULL, '9' FROM DUAL;
<强>查询强>:
SELECT Aid FROM A
MINUS
SELECT Aid FROM B
MINUS
SELECT Aid FROM C
MINUS
SELECT Aid FROM D
<强>输出强>:
AID
---
2
3
更新以获取A
的所有列:
这将排除Aid
相等或两者都为NULL
的行:
SELECT *
FROM A
WHERE NOT EXISTS(SELECT 1 FROM B WHERE A.Aid = B.Aid OR (A.Aid IS NULL AND B.Aid IS NULL))
AND NOT EXISTS(SELECT 1 FROM C WHERE A.Aid = C.Aid OR (A.Aid IS NULL AND C.Aid IS NULL))
AND NOT EXISTS(SELECT 1 FROM D WHERE A.Aid = D.Aid OR (A.Aid IS NULL AND D.Aid IS NULL));
答案 2 :(得分:2)
SELECT A.aid
FROM A
WHERE NOT EXISTS (select 1 from B where B.aid = A.aid) AND
NOT EXISTS (select 1 from C where C.aid = A.aid) AND
NOT EXISTS (select 1 from D where D.aid = A.aid)
答案 3 :(得分:2)
请使用以下查询,它将完美运作。
select * from #A where Aid not in (select Aid From #B
UNION
select Aid From #C
Union
select Aid From #D)
答案 4 :(得分:1)
使用NOT IN
运算符
Select * from A
Where Aid not in (
Select Aid from B
Union all
Select Aid from C
Union all
Select Aid from D
)
ert that ..如果表A中援助无效,但B,C&amp; D没有null, null将不会被返回。在这种情况下,左连接是优越的... - JGFMK 43分钟前
如果表A在aid
列中包含NULL,则左连接查询将始终返回该行,而不管其他表中是否会出现NULL。请检查这个简单的测试用例http://rextester.com/ESZWH45744