我在下面有一个SQL查询:
SELECT
md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther
FROM
marketing_details md
WHERE
md.id = 14588
在上面的select语句中的7列中,只有一列具有值,而rest将为null。是否可以使用某种sql语句选择那个非空的列值?
答案 0 :(得分:4)
使用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值的字段的名称,那么您可以使用下面的以下monstrous 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
嗯,我希望我把所有的括号都弄好了!