使用coalesce() 函数从参数列表中返回第一个非空值:
SELECT
coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther) as non_null_value
FROM
marketing_details md
WHERE
md.id = 14588
但是,它无法告诉您该值来自哪一列。
更新
如果你真的想使用 sql 来检索具有非 null 值的字段的名称,那么你可以使用下面的下面这个怪异的 sql 语句来做到这一点。它的作用是将记录中的每个字段值连接成一个字符串,其中的值用逗号分隔。 NULL 值被转换为空字符串。然后使用find_in_set() 函数找到上述字符串中唯一非空值的位置。然后使用elt() 函数,它根据find_in_set() 返回的位置从字段名称文字列表中返回字段名称。
SELECT
md.id,
coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther) as non_null_value,
elt(find_in_set(coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther),
concat(coalesce(md.refereeInternetSearch,''),',',
coalesce(md.refereeCompanyColleague,''),',',
coalesce(md.refereeIndustryPeer,''),',',
coalesce(md.refereeIndustryEvent,''),',',
coalesce(md.refereeIndustryPublication,''),',',
coalesce(md.refereeMarketingEmail,''),',',
coalesce(md.refereeOther,'')
)
),'refereeInternetSearch',
'refereeCompanyColleague',
'refereeIndustryPeer',
'refereeIndustryEvent',
'refereeIndustryPublication',
'refereeMarketingEmail',
'refereeOther'
) as field_name
FROM
marketing_details md
WHERE
md.id = 14588
嗯,我希望我把所有的括号都记对了!