使用通配符/默认值加入表

时间:2014-06-09 20:24:26

标签: sql join sql-server-2008-r2 wildcard

我正在尝试连接两个表并使用*连接任何具有空字符串的行...

例如

表A:

Fund Name, Fund Code
Fund A, 12345
Fund B, 34567
Fund C, 99999
Fund D, 44444

表B:

Fund Name, FundMail
Fund A, johndoe@gmail.com
Fund B, janedoe@gmail.com
*, default@gmail.com

期望的结果:

Fund A, 12345, johndoe@gmail.com
Fund B, 34567, janedoe@gmail.com
Fund C, 99999, default@gmail.com
Fund D, 44444, default@gmail.com

我用谷歌搜索了一下但似乎无法绕过它......

2 个答案:

答案 0 :(得分:1)

你的意思是这样吗?

select a.FundName, a.FundCode, b.FundMail
from tableA a join
     tableB b
     on a.FundName = b.FundName or b.FundName = '*';

这不是很正确,因为所有内容都会与*匹配,因此以上内容会返回重复的行。

它认为你想要这样说:

select a.FundName, a.FundCode, coalesce(b.FundMail, bd.FundMail) as FundMail
from tableA a left join
     tableB b
     on a.FundName = b.FundName left join
     tableB bd
     on b.FundName = '*';

答案 1 :(得分:0)

我会分2步完成:

declare @defaultEmail varchar(50)

select @defaultEmail = fundMail
from tableB
where FundName = '*'

select a.FundName, 
a.FundCode, 
isnull(b.fundMail, @defaultEmail) as EMail
from tableA as a
left join tableB as b
on a.FundName = b.FundName
order by 1, 2