![](/img/trans.png)
[英]Select records from table where a given column value has no non-null values in another column
[英]MySQL Return the first non-NULL value from the list of the column in select statement with column name
我在下面有一個 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 列中,只有一列有值,其余為空。 是否可以使用某種 sql 語句只選擇一個不為空的列值?
使用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 來檢索具有非空值的字段的名稱,那么您可以使用下面的以下 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
呵呵,我希望我把所有的括號都說對了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.