在Oracle中,是否可以执行union重复条件在单个列而不是整行的位置?
我有表A,并B有2列:item_name, price.我想创建一个视图,对于某些item_names,它看起来在表A,看是否item_name存在,如果是这样使用price的A,如果不是去B和使用price中B,然后union将其余item_name的B尚未被添加到了视野.
例如,
Table A Table B
---------------- ----------------
item_name price item_name price
---------------- ----------------
shoe 10 shoe 8
socks 2 socks 4
shirt 5 t-shirt 3
gloves 1 glasses 15
pants 7
Run Code Online (Sandbox Code Playgroud)
对于shoe和socks我想使用table A的价格,如果可用,如果不使用table B.所以最后,我的观点应该是这样的:
View
-----------------------
item_name price source
-----------------------
shoe 10 A
socks 2 A
t-shirt 3 B
glasses 15 B
pants 7 B
Run Code Online (Sandbox Code Playgroud)
我试过了
select * from A a
where item_name in ('shoe', 'socks')
union
select * from B b
where b.item_name not in
(select item_name from A
where item_name in ('shoe', 'socks'))
Run Code Online (Sandbox Code Playgroud)
我不喜欢,因为查询select * from A where item_name in ('shoe', 'socks')是重复的.有更好/更有效的方法吗?
我想你正在寻找一个加入:
select coalesce(a.item_name, b.item_name) as item_name,
coalesce(a.price, b.price) as price,
(case when a.price is not null then 'A' else 'B' end) as source
from a full outer join
b
on a.item_name = b.item_name
Run Code Online (Sandbox Code Playgroud)