MySQL 从带有列名的 select 语句中的列列表中返回第一个非 NULL 值

use*_*307 3 mysql select

我在下面有一个 sql 查询:

SELECT 
    md.refereeInternetSearch,
    md.refereeCompanyColleague,
    md.refereeIndustryPeer,
    md.refereeIndustryEvent,
    md.refereeIndustryPublication,
    md.refereeMarketingEmail,
    md.refereeOther
FROM
    marketing_details md
WHERE
    md.id = 14588
Run Code Online (Sandbox Code Playgroud)

在上述 select 语句的 7 列中,只有一列有值,其余为空。是否可以使用某种 sql 语句只选择一个不为空的列值?

Sha*_*dow 7

使用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
Run Code Online (Sandbox Code Playgroud)

但是,它无法告诉您该值来自哪一列。

更新

如果您真的想使用 sql 来检索具有非空值的字段的名称,那么您可以使用下面的以下 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
Run Code Online (Sandbox Code Playgroud)

呵呵,我希望我把所有的括号都说对了!