我正在尝试对以下两个表进行联接:
table 1
id addr
1 Mumbai
2 delhi
3 Orissa
table 2
flight add
y mum
y del
n ori
我的SQL查询是:
select
b.flight,
a.id
from table2 b
join table1 a
on b.add = (select case when a.addr = 'Mumbai' then 'mum'
when a.addr = 'Delhi' then 'del
end);
在Netezza上运行时,出现以下错误:
This form of correlated query is not supported - consider rewriting
有人可以告诉我正确的方法吗?
答案 0 :(得分:2)
case
是一个表达式,就像其他任何表达式一样。您在那里不需要相关查询,只需直接使用表达式即可:
select
b.flight,
a.id
from table2 b
join table1 a
on b.add = case when a.addr = 'Mumbai' then 'mum'
when a.addr = 'Delhi' then 'del
end;
答案 1 :(得分:1)
您可以根据需要使用SUBSTRING
和LOWER
select
b.flight,
a.id
from table2 b
join table1 a
on b.add = SUBSTRING(LOWER(a.addr), 1, 3)
答案 2 :(得分:1)
我无法确定Netezza是否支持这种联接,但是您可以在以下子查询中移动case语句:
select
b.flight,
a.id
from table2 b join (
select id,
case addr
when 'Mumbai' then 'mum'
when 'Delhi' then 'del'
end addr
from table1
) a on b.add = a.addr;
答案 3 :(得分:1)
如果您要查找表1中以表2中的值addr
开头的add
,写此联接的一种简单方法是使用Like
select b.flight
, a.id
from table1 as a
join table2 as b on a.addr like b.[add] + '%'
答案 4 :(得分:1)
如果您只想将'Mumbai'与'mum'结合在一起,并将'delhi'与'del'结合起来,则只需检查配对:
select b.flight, a.id
from table2 b
join table1 a on (b.add = 'mum' and a.addr = 'Mumbai')
or (b.add = 'del' and a.addr = 'delhi')
如您所见,在CASE WHEN
和WHERE
条件下不需要ON
,只需使用AND
和OR
。
我不认识Netezza。也许它甚至支持元组:
select b.flight, a.id
from table2 b
join table1 a on (b.add, a.addr) in (('mum', 'Mumbai'), ('del', 'delhi'))