我有两个列完全相同的表
表A
id FLAG 1 Y 2 Y 3 N 4 N
表B
id FLAG 1 Y 2 3 N 4
我想在Oracle中编写一个select查询,它将显示表A中的所有行,其中FLAG
列与表B不同但具有匹配的ID列
结果如下:
id FLAG 2 Y 4 N
答案 0 :(得分:3)
“表A中的所有行...表B具有匹配的ID列”:
FROM a JOIN b USING (id)
“FLAG列不相同”:
WHERE a.flag != b.flag
OR (a.flag IS NULL AND b.flag IS NOT NULL)
OR (b.flag IS NULL AND a.flag IS NOT NULL)
所以,查询将是
SELECT id, a.flag
FROM a JOIN b USING (id)
WHERE a.flag != b.flag
OR (a.flag IS NULL AND b.flag IS NOT NULL)
OR (b.flag IS NULL AND a.flag IS NOT NULL)
WHERE
- 条件是丑陋的但是必须要抓住表b具有NULL
- 值的情况,但不是,或者反过来......
答案 1 :(得分:2)
这个在oralce中工作..因为列中有null。它不能直接比较所以需要使用 NVL()或等效函数
select a1.* from table_a a1,table_b b
where A1.id=B.id
and nvl(a1.flag,'y')<>nvl(b.flag,'y')
请参阅此sqlfiddle:http://sqlfiddle.com/#!4/241de/1
答案 2 :(得分:1)
这样做,
select Table_A.id,Table_A.FLAG from
Table_A join Table_b on Table_A.id=Table_b.id
where Table_A.FLAG!=Table_b.FLAG
or (Table_b.FLAG is null and table_a.flag is not null);
答案 3 :(得分:0)
怎么样
SELECT *
FROM TABLEA
INNER JOIN TABLEB
ON TABLEA.ID = TABLEB.ID
WHERE TABLEA.Flag != TABLEB.FLAG
OR TABLEB.FLAG IS NULL
答案 4 :(得分:0)
假设是这种情况,您可以使用..
获取详细信息select a.id, a.flag, b.flag
from table_a a,
table_b b
where a.id = b.id(+)
因为你需要标志不相等的行..
select a.id, a.flag, b.flag
from table_a a,
table_b b
where a.id = b.id(+)
and a.flag <> b.flag
同时检查标志是否为null,在这种情况下查询可能需要稍微更改一下。
答案 5 :(得分:0)
SELECT a.*
FROM tableA a
LEFT JOIN tableB b
ON a.id = b.ID AND
a.FLAG = b.FLAG
WHERE b.ID IS NULL
答案 6 :(得分:0)
在我看来,你在开玩笑:) 在这种情况下,Oracle有特殊的MINUS运算符。 Proof link
所以答案非常简短
select id, flag from a
minus
select id, flag from b
P.S。抱歉 - 或者表B中必须有相应ID的记录? 然后看下面的
select id, flag from a where id in (select id from b)
minus
select id, flag from b