我有以下数据:
tblBio
bio bioid
some data 1
some data 2
tblContact
email email_pub bioid
me@me.com 1 1
you@me.com 0 2
我需要选择
bio + 'email: ' + email WHERE email_pub = 1
我目前有:
SELECT b.bio + 'Email: ' + COALESCE(c.email, '')
FROM tblbio b
INNER JOIN tblContact c ON b.bioid = c.bioid
WHERE c.email_pub = 1
AND b.bioid = 1
但是,我总是需要选择bio然后将文本'email:'以及电子邮件地址附加到最后,如果email_pub设置为1.拥有'WHERE email_pub = 1'使得如果email_pub为0然后没有选择任何内容。
同样,即使没有发布的电子邮件,也会始终显示“电子邮件:”文本。
谢谢,
托马斯
答案 0 :(得分:6)
这是一种需要CASE
- CASE
的方案,用于内联评估表达式。
SELECT b.bio + 'Email: ' + CASE WHEN email_pub=1 THEN COALESCE(c.email, '') ELSE '' END
FROM tblbio b
INNER JOIN tblContact c ON b.bioid = c.bioid
WHERE b.bioid = 1
答案 1 :(得分:5)
使用CASE
:
SELECT b.bio + case when email_pub = 1 then 'Email: ' + COALESCE(c.email, '') else '' end
FROM tblbio b
INNER JOIN tblContact c ON b.bioid = c.bioid
WHERE b.bioid = 1