在Oracle中,是否可以在union中对单个列而不是整行执行重复条件?
我有表A和B,它们有两列:item_name, price。我想创建一个视图,对于某些item_names,它在表A中查找item_name是否存在,如果存在,则使用A中的price,如果不存在,则转到B并使用B中的price,然后对<代码>D14中尚未添加到视图的<代码>d13的其余部分执行union操作。
例如,
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对于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我试过了
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'))我不喜欢这样,因为查询select * from A where item_name in ('shoe', 'socks')是重复的。有没有更好/更有效的方法来做到这一点?
发布于 2012-12-18 22:26:57
我认为你正在寻找一个连接:
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发布于 2012-12-18 22:41:21
既然你使用的是Oracle,我建议你这样做:
select NVL(A.ITEM_NAME,B.ITEM_NAME) AS ITEM_NAME,
NVL(A.PRICE,B.PRICE) AS PRICE
FROM A as a RIGHT JOIN B as b ON A.ITEM_NAME=B.ITEM_NAME要理解它的工作原理,只需在不使用NVL的情况下尝试它,结果是右连接结果
A_item A_price B_item B_price
shoe 10 shoe 8
socks 2 socks 4
(null) (null) glasses 15
(null) (null) t-shirt 3
(null) (null) pants 7由于您不需要表A中的空值,因此请使用NVL
NVL在mysql/mssql等语言中也有相当的功能
发布于 2012-12-18 22:31:13
尝尝这个,
create view viewname as (
select coalesce(a.item_name, b.item_name) as item_name,
coalesce(a.price, b.price) as price,
(case when a.item_name=b.item_name then 'A' else 'B' end) as source
from tablea a right outer join
tableb b
on a.item_name = b.item_name)对戈登的ans做了一些小改动
https://stackoverflow.com/questions/13934995
复制相似问题