Oracle sql查询联合操作?
我有两张桌子<代码>表A和Oracle sql查询联合操作?,sql,oracle,Sql,Oracle,我有两张桌子表A和表B。这两个表都有一些包含两列的数据,如下所示 TableA --------- id Name --- ---- 1 abc 2 def TableB --------- id Name --- ---- 1 xyz 2 pqr 现在,我将从我的应用程序中传递ID列表,并获得相同的ID及其名称,如下所示: select id, name from TableA where id in(1,2) union select id, name fro
表B
。这两个表都有一些包含两列的数据,如下所示
TableA
---------
id Name
--- ----
1 abc
2 def
TableB
---------
id Name
--- ----
1 xyz
2 pqr
现在,我将从我的应用程序中传递ID列表,并获得相同的ID及其名称,如下所示:
select id, name
from TableA
where id in(1,2)
union select id, name
from TableB
where id in(1,2);
上述查询给出的结果如下:
1 abc
1 xyz
2 def
2 pqr
但我需要的是,如果两个表中存在相同的id,那么应该考虑TableB的名称,而不是TableA的名称
Expected output:
1 xyz
2 pqr
还有一个问题是,如果TableB不包含任何数据,那么应该提取TableA的数据
我该怎么做
谢谢 试试这个:
select id, name from TableA where id in(1,2) and id not in ( select id from TableB) a union select id, name from TableB where id in(1,2);
使用简单的联合尝试此查询,您可以合并记录
SELECT id, name from tableA where id not in (SELECT id FROM tableB)
UNION ALL
SELECT id, name from tableB
试试这个
SELECT id , name from (
select id, name from TableA where id in(1,2)
union select id, name from TableB where id in(1,2)) t
GROUP BY id;
请尝试使用左连接
SELECT TableA.ID,
NVL(TableB.Name, TableA.Name) Name FROM
TableA LEFT JOIN TableB
ON TableA.ID=TableB.ID
WHERE TableA.ID IN (1, 2)
使用Union All和exists/not exists可根据表_b中是否存在任何记录来控制从表_a返回哪些结果
select id,name
from (
select id,name
from table_b
union all
select id,name
from table_a
where exists (select null from table_b) and
not exists (
select null
from table_b
where table_b.id = table_a.id)
union all
select id,name
from table_a
where not exists (select null from table_b))
where id in (1,2)
如果行可以是A、A+B或B,一种方法是(如果
表A
总是有数据,那么techdo的答案更好):
减号运算符-仅返回第一个查询返回的唯一行,但不返回第二个查询返回的唯一行:
WITH tab_a AS
(
SELECT 1 id, 'abc' val FROM dual
UNION
SELECT 2, 'def' FROM dual
),
tab_b AS
(
SELECT 1, 'xyz' val FROM dual
UNION
SELECT 2, 'pqr' FROM dual
)
-- This is your query --
SELECT * FROM tab_b
MINUS
SELECT * FROM tab_a
/
ID VAL
----------
1 xyz
2 pqr
下面的代码用于从两个表(A+B)中选择数据,然后使用减号和join取出不需要的行的数据。如果从表A而不是表B中选择名称的需求发生变化,那么代码可以很容易地修改
select * from tableA where id in (1,2)
union
select * from tableB where id in (1,4)
minus
select a,id, a.Name from tableA a join tableB b on a.id = b.id where
a.id in (1,2);
谢谢你的回复。如果表B中没有任何数据,该查询是否有效。如果TableB不包含任何数据,我仍然需要TableA中的数据您只需要使用union或其他集合运算符?虽然此代码段可能是解决方案,但包含解释确实有助于提高您的文章质量。请记住,您将在将来回答读者的问题,而这些人可能不知道您的代码建议的原因
WITH tab_a AS
(
SELECT 1 id, 'abc' val FROM dual
UNION
SELECT 2, 'def' FROM dual
),
tab_b AS
(
SELECT 1, 'xyz' val FROM dual
UNION
SELECT 2, 'pqr' FROM dual
)
-- This is your query --
SELECT * FROM tab_b
MINUS
SELECT * FROM tab_a
/
ID VAL
----------
1 xyz
2 pqr
select * from tableA where id in (1,2)
union
select * from tableB where id in (1,4)
minus
select a,id, a.Name from tableA a join tableB b on a.id = b.id where
a.id in (1,2);