MySQL - 仅在非空时连接
MySQL - Concat only when not empty
当我从数据库中 return 时,我试图将 link 添加到我的图像,但我不想在图像为空时添加它。我尝试了 CONCAT
和 CONCAT_WS
但没有用
这两个都不起作用:
SELECT id, name_en as name, CONCAT_WS("http://website.com/", image) as image FROM businesses
SELECT id, name_en as name, CONCAT("http://website.com/", image) as image FROM businesses
您正在寻找的是 COALESCE() 函数:下面的 link 文档。它 returns 系列中的第一个非空值。所以本质上我们用空字符串替换 Null。
SELECT id, name_en as name, CONCAT("http://website.com/", coalesce(image,'')) as image
FROM businesses
https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce
您可以使用 ÌF
流控制`来确定图像是否为 NULL,如果不是则添加 url
SELECT id, name_en as name, IF(image IS NOT NULL, CONCAT("http://website.com/", image),"") as image
FROM businesses
当我从数据库中 return 时,我试图将 link 添加到我的图像,但我不想在图像为空时添加它。我尝试了 CONCAT
和 CONCAT_WS
但没有用
这两个都不起作用:
SELECT id, name_en as name, CONCAT_WS("http://website.com/", image) as image FROM businesses
SELECT id, name_en as name, CONCAT("http://website.com/", image) as image FROM businesses
您正在寻找的是 COALESCE() 函数:下面的 link 文档。它 returns 系列中的第一个非空值。所以本质上我们用空字符串替换 Null。
SELECT id, name_en as name, CONCAT("http://website.com/", coalesce(image,'')) as image
FROM businesses
https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce
您可以使用 ÌF
流控制`来确定图像是否为 NULL,如果不是则添加 url
SELECT id, name_en as name, IF(image IS NOT NULL, CONCAT("http://website.com/", image),"") as image
FROM businesses