内部查询的SQL帮助

时间:2014-04-07 12:57:57

标签: sql oracle10g toad

对不起重新发布,但这有助于您更好地了解scnario- 对于每个成员,可以有两种类型的地址(邮件和法律 - 基于两个差异指示符)。我的目标是提取地址并在每个成员ID的一列中显示它们。

TABLE1

Address_key(PK)  Country  City      PostCode
1                UK       London    1111
2                US       New York  2222
3                Spain    Madrid    3333
4                France   Paris     4444
5                Swiss    Munich    5555

表2

Member Key(PK)   Memebr ID
1                1
2                2
3                3
4                2

表3

Address Key   Member Key    Mail Ind   Legal Ind
1             1             Y          N
2             1             N          Y
3             2             Y          Y
4             4             N          Y
5             4             Y          N

我的目标是获取每个会员ID的邮件地址(基于邮件ind)和合法地址(基于legal ind)。 所以我的输出应该是 -

Member Key   Member ID   Country   City    Postcode   Legal Country   Legal City   Legal Postcode
1            1           UK        London  1111       US              New York     2222
2            2           Spain     Madrid  3333       Spain           Madrid       3333         
4            2           Swiss     Munich  5555       France          Paris        4444

任何人都可以帮助如何实现这一目标吗?我正在使用oracle 10m toad 9.0
哪个更好用:内部查询或简单连接?

2 个答案:

答案 0 :(得分:0)

如下所示?您的列命名与Table2成员密钥(PK),Memebr ID以及它们与表3成员ID的关系有点混淆。我的最佳猜测如下:

Select [Member Key], t2.[Member Id], t1.*
FROM TABLE2 t2
INNER JOIN TABLE3 t3 on t3.[Member Key] = t2.[Member Id]
INNER JOIN TABLE1 t1 on t1.[Address Key] = t3.[Address Key]

答案 1 :(得分:0)

由于您有两种类型的地址,您可以连接两次到TABLE3,一次连接到邮件地址,下一次连接到合法地址。

select T2.Member_Key, T2.Member_id
       ,coalesce(T1A.Country,''), coalesce(T1A.City,''), coalesce(T1A.PostCode,'')
       ,coalesce(T1B.Country,''), coalesce(T1B.City,''), coalesce(T1B.PostCode,'')
from Table2 T2
left join Table3 T3A on T2.Member_Key=T3A.Member_Key and T3A.Mail_Ind='Y'
left join Table1 T1A on T3A.Address_key = T1A.Address_Key
left join Table3 T3B on T2.Member_Key=T3B.Member_Key and T3B.Legal_Ind='Y'
left join Table1 T1B on T3B.Address_key = T1B.Address_Key

另一种方法是连接一次并使用CASE表达式,因此:

select T2.Member_Key, T2.Member_id
       ,max(coalesce(CASE T3.Mail_Ind='Y'  then T1.Country Else '' End,''))
       , ... etc.
       ,max(coalesce(CASE T3.Legal_Ind='Y' then T1.Country Else '' End,''))
       , ... etc.
from Table2 T2
left join Table3 T3 on T2.Member_Key=T3.Member_Key 
left join Table1 T1A on T3.Address_key = T1.Address_Key
group by Member_Key, Member_id